Absurd Loop Problem

Reply

Join Date: Oct 2008
Posts: 15
Reputation: thanatosys is an unknown quantity at this point 
Solved Threads: 1
thanatosys thanatosys is offline Offline
Newbie Poster

Absurd Loop Problem

 
0
  #1
Nov 20th, 2008
Ok I will post all of the code at the bottom, first thing however is the loop below starts at 0, then increments to 1, but never increments any further.

  1. for counter1 in range(fieldlength):
  2. if self.__fields[counter1] == field:
  3. for counter2 in range(rowlength):
  4. #print self.__rows[counter2][counter1]
  5. if self.__rows[counter2][counter1] == value:
  6. return1 = counter2
  7. matchcount = matchcount + 1
  8. print "The Match count is INSIDE THE LOOP: " + str(matchcount)
  9. counter2 = counter2 + 1
  10. counter1 = counter1 + 1

This is the test code that should cause the loop to go above 1:
  1. T = SDBTable('id=ui', 'last', 'first', 'age=i', 'married=b', 'salary=f')
  2. print T
  3.  
  4. print '# insert 6 rows'
  5. T.insert(1, 'Jones', 'Bobby', 55, True, 98765.43)
  6. T.insert(2, 'Jones', 'Jack', 15, False, 0.0)
  7. T.insert(3, 'Smith', 'Jack', 66, True, 88.88)
  8. T.insert(4, 'Jones', 'Mark', 50, True, 100.0)
  9. T.insert(5, 'Smith', 'Mark', 5, False, 10000.00)
  10. T.insert(6, 'Jones', 'Dave', 9, False, 123.45)
  11.  
  12. print '# get works:'
  13. print T.get('first', 'Bobby')
  14.  
  15. print '# get fails'
  16. try:
  17. T.get('last', 'Jones')
  18. except SDBError, e:
  19. print e

Any ideas on how to solve matchcounters fear of numbers larger than 1?

Shell output:
  1. $ python test.py
  2. # create table
  3. TABLE<id,last,first,age,married,salary>
  4. # insert 6 rows
  5. # get works:
  6. The Match count is INSIDE THE LOOP: 1
  7. The Match count is : 1
  8. ROW<1,Jones,Bobby,55,True,98765.43>
  9. # get fails
  10. The Match count is INSIDE THE LOOP: 1
  11. The Match count is : 1

sdb.py:
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """
  4. sdb.py
  5. Simple DB
  6.  
  7. Created by Christopher King on 2008-10-29.
  8. Copyright (c) 2008 NCSU. All rights reserved.
  9. """
  10.  
  11. # Error classes. One base class and 4 derived classes.
  12. # NOTE: there is no need to modify any of the error classes
  13. #
  14.  
  15. import sys, string, operator, types
  16. class SDBError(Exception):
  17. """Base class for SDB.
  18. """
  19. def __init__(self, msg):
  20. self.msg = msg
  21. def __str__(self):
  22. return repr(self.msg)
  23.  
  24. class SDBInsertError(SDBError):
  25. """Insertion error class.
  26. Attribute: msg.
  27. """
  28. pass
  29.  
  30. class SDBUpdateError(SDBError):
  31. """Update error class.
  32. Attributes: field, msg.
  33. """
  34. def __init__(self, field, msg):
  35. self.field, self.msg = field, msg
  36. def __str__(self):
  37. return self.field + ": " + self.msg
  38.  
  39. class SDBFetchError(SDBError):
  40. """Fetch error class.
  41. Attribute: msg.
  42. """
  43. pass
  44.  
  45. class SDBUsageError(SDBError):
  46. """Usage error class.
  47. Attribute: msg.
  48. """
  49. pass
  50.  
  51. # the primary db class
  52. #
  53. class SDBTable:
  54. """Class for SDB table.
  55. """
  56.  
  57. # suggested private variables
  58. __rows = [] # stores SDBRows
  59. __fields = [] # stores field names
  60. __specs = [] # stores specification of each field
  61. # which is a tuple(bool, type)
  62. # tuple[0] answers is unique?
  63. # tuple[1] answers what type?
  64. # NOTE: len(__fields) == len(__specs)
  65.  
  66. def __init__(self, *fields):
  67. """
  68. Create a table. The parameters define valid fields/columns in
  69. the table. There is at least one parameter.
  70.  
  71. Field specifiers have a name and an option attribute.
  72.  
  73. Name is a valid Python string.
  74.  
  75. Attribute list begins with a '=' has one or two attribute values.
  76.  
  77. Attributes:
  78. s,i,f,b = type: str, int, float, bool [default: str]
  79. u = unique (ie, a key field) [default: false]
  80.  
  81. Example: field specifier:
  82.  
  83. first_name # string field
  84. id=iu # unique integer field
  85. age=i # integer field
  86. program=u # unique string
  87. salary=uf # unique float
  88. """
  89. counter = 0
  90. for f in fields:
  91. # test the format and determine name, unique, and type
  92. # ...
  93. #print fields[counter].count("=")
  94. splitfield = fields[counter].split('=')
  95. if fields[counter].count("=") == 0:
  96. self.__fields.append(str(splitfield[0]))
  97. self.__specs.append((False, str))
  98. else:
  99. self.__fields.append(str(splitfield[0]))
  100. if str(splitfield[1]).count("s") == 1:
  101. if str(splitfield[1]).count("u") == 1:
  102. self.__specs.append((True, str))
  103. else:
  104. self.__specs.append((False, str))
  105. elif str(splitfield[1]).count("i"):
  106. if str(splitfield[1]).count("u") == 1:
  107. self.__specs.append((True, int))
  108. else:
  109. self.__specs.append((False, int))
  110. elif str(splitfield[1]).count("f"):
  111. if str(splitfield[1]).count("u") == 1:
  112. self.__specs.append((True, float))
  113. else:
  114. self.__specs.append((False, float))
  115. elif str(splitfield[1]).count("b"):
  116. if str(splitfield[1]).count("u") == 1:
  117. self.__specs.append((True, bool))
  118. else:
  119. self.__specs.append((False, bool))
  120. counter = counter + 1
  121.  
  122. def get(self, field, value):
  123. #del self.__rows[self.__rows.index(row)]
  124. """
  125. Returns the row in which field=value.
  126. Returns None if no match.
  127. Raises SDBFetchError if more than 1 row matches.
  128. """
  129.  
  130. rowlength = (self.size())
  131. rowlength = rowlength / len(self.__fields)
  132. fieldlength = len(self.__fields)
  133. counter1 = 0
  134. counter2 = 0
  135. return1 = 0
  136. matchcount = 0
  137. for counter1 in range(fieldlength):
  138. if self.__fields[counter1] == field:
  139. for counter2 in range(rowlength):
  140. #print self.__rows[counter2][counter1]
  141. if self.__rows[counter2][counter1] == value:
  142. return1 = counter2
  143. matchcount = matchcount + 1
  144. print "The Match count is INSIDE THE LOOP: " + str(matchcount)
  145. counter2 = counter2 + 1
  146. counter1 = counter1 + 1
  147. print "The Match count is : " + str(matchcount)
  148. if (matchcount > 1):
  149. raise SDBFetchError(matchcount)
  150. else:
  151. return self.__rows[return1]
  152. pass
  153.  
  154. def filter(self, compare):
  155. """
  156. Returns list of all rows that match compare.
  157. Two kinds of comparisons.
  158.  
  159. Simple is equality on one field. Value is of parameter must be
  160. a string that is field=value (no spaces).
  161.  
  162. The parameter for complex compare is a function that accepts
  163. a tuple as its only parameter and returns a boolean whether the
  164. row matches.
  165.  
  166. Raises SDBUsageError if there is any problem with the parameters.
  167. """
  168.  
  169. if compare.__class__ == str:
  170. # do a simple filter
  171. pass
  172. else:
  173. # do a complex filter
  174. pass
  175.  
  176. def insert(self, *values):
  177. """
  178. Inserts a row into the table. The number of parameters must
  179. match the number the defined for the table.
  180.  
  181. This method checks that the values are the proper type and,
  182. if necessary, whether it is unique.
  183.  
  184. Raises SDBInsertError if the is a problem.
  185.  
  186. On success, returns the newly created SDBRow
  187. """
  188.  
  189. # check all the values
  190. counter = 0
  191. arglength = len(values)
  192. tablelength = len(self.__fields)
  193. #existingtype = type(self.__specs[3][1])
  194. #existingtype = existingtype.__name__
  195. existingtype = self.__specs[1][1].__name__
  196. #print existingtype
  197. counter = 0
  198. if (arglength == tablelength):
  199.  
  200. for f in values:
  201. #print f
  202. existingtype = self.__specs[counter][1].__name__
  203. valuetype = type(values[counter])
  204. valuetype = valuetype.__name__
  205. if valuetype == existingtype:
  206.  
  207. #print "Input value Type: " + valuetype
  208. #print "Existing value Type: " + existingtype
  209. #print "Counter is presently: " + str(counter)
  210. counter = counter + 1
  211. row = SDBRow(self, values)
  212. self.__rows.append(row)
  213. return row
  214. else:
  215. SDBInsertError()
  216.  
  217. else:
  218. raise SDBInsertError()
  219.  
  220.  
  221. def remove(self, row):
  222. """
  223. Removes row from table.
  224.  
  225. Raise exception if row is not in table.
  226. """
  227. errorcount = 0
  228. rowlength = (self.size())
  229. rowlength = rowlength / len(self.__fields)
  230. while counter < rowlength:
  231. if self.__rows[counter] == row:
  232. errorcount = 20
  233. del self.__rows[self.__rows.index(row)]
  234. if (errorcount != 20):
  235. raise SDBUsageError()
  236.  
  237. def field_index(self, field):
  238. """
  239. returns the index and the specifier for field.
  240. """
  241. return self.__fields.index(field)
  242.  
  243. def field_specs(self, idx):
  244. """
  245. returns the index and the specifier for field.
  246. """
  247. return self.__specs[idx]
  248.  
  249. def size(self):
  250. return len(self.__rows)
  251.  
  252. def __str__(self):
  253. return "TABLE<" + ','.join(self.__fields) + ">"
  254.  
  255. # the row class
  256. # NOTE: there is no need to change this
  257. #
  258. class SDBRow:
  259. """Class for SDB row.
  260. """
  261.  
  262. __table = None
  263. __values = None
  264.  
  265. def __init__(self, table, values):
  266. """Initialize a row. Save a reference to the table it belongs to.
  267. Store values as a list
  268. """
  269. self.__table = table
  270. self.__values = list(values)
  271.  
  272. def set(self, field, value):
  273. """Set a field in an existing row.
  274. Must look up the field name and specification in self.__table.
  275. """
  276. idx = self.__table.field_index(field)
  277. specs = self.__table.field_specs(idx)
  278. if specs[1] != value.__class__:
  279. raise SDBException, "wrong type for %s" % field
  280. if specs[0]:
  281. # must be unique, use table's get method
  282. try:
  283. if self.__table.get(field, value):
  284. raise SDBUpdateError(field, "value is not unique")
  285. except SDBFetchError:
  286. # multiple entries
  287. raise SDBUpdateError(field, "value is not unique")
  288. self.__values[idx] = value
  289.  
  290. def __getitem__(self, idx):
  291. if type(idx) == int:
  292. return self.__values[idx]
  293. else:
  294. return self.__values[self.__table.field_index(idx)]
  295.  
  296. def __str__(self):
  297. return "ROW<" + ','.join([str(v) for v in self.__values]) + ">"

test.py:
  1. #!/usr/bin/python
  2.  
  3. from sdb import SDBTable, SDBError
  4.  
  5. # create a table and insert
  6. print '# create table'
  7. T = SDBTable('id=ui', 'last', 'first', 'age=i', 'married=b', 'salary=f')
  8. print T
  9.  
  10. print '# insert 6 rows'
  11. T.insert(1, 'Jones', 'Bobby', 55, True, 98765.43)
  12. T.insert(2, 'Jones', 'Jack', 15, False, 0.0)
  13. T.insert(3, 'Smith', 'Jack', 66, True, 88.88)
  14. T.insert(4, 'Jones', 'Mark', 50, True, 100.0)
  15. T.insert(5, 'Smith', 'Mark', 5, False, 10000.00)
  16. T.insert(6, 'Jones', 'Dave', 9, False, 123.45)
  17.  
  18. print '# get works:'
  19. print T.get('first', 'Bobby')
  20.  
  21. print '# get fails'
  22. try:
  23. T.get('last', 'Jones')
  24. except SDBError, e:
  25. print e
  26.  
  27. print '# filter finds 4'
  28. for r in T.filter('last=Jones'):
  29. print r
  30. print '# filter finds 2'
  31. for r in T.filter('first=Mark'):
  32. print r
  33. print '# filter finds 0'
  34. for r in T.filter('last=jones'):
  35. print r
  36.  
  37. print '# lambda filter finds 2'
  38. for r in T.filter(lambda row: row[5] > 80.0 and row[5] < 101):
  39. print r['last'], r['first']
  40.  
  41. print '# row operations'
  42. r = T.get('id', 1)
  43. print 'last:', r[1], r['last']
  44. print 'test set'
  45. print r
  46. r.set('last', 'Merkel')
  47. print r
  48. print '# test set unique'
  49. try:
  50. r.set('id', 2)
  51. except SDBError, e:
  52. print e
  53.  
  54. print '# test remove, size'
  55. print 'size', T.size()
  56. T.remove(r)
  57. print 'row?', T.get('id', 1)
  58. print 'size', T.size()

Thanks in advance.
Last edited by thanatosys; Nov 20th, 2008 at 12:23 pm.
Reply With Quote Quick reply to this message  
Join Date: Dec 2006
Posts: 1,008
Reputation: woooee is a jewel in the rough woooee is a jewel in the rough woooee is a jewel in the rough 
Solved Threads: 285
woooee woooee is offline Offline
Veteran Poster

Re: Absurd Loop Problem

 
0
  #2
Nov 20th, 2008
I would suggest the following print statements to clarify things.
  1. print "length of self.__fields =", fieldlength
  2. for counter1 in range(fieldlength):
  3. if self.__fields[counter1] == field:
  4. print "counter1 == field"
  5. for counter2 in range(rowlength):
  6. #print self.__rows[counter2][counter1]
  7. if self.__rows[counter2][counter1] == value:
  8. return1 = counter2
  9. matchcount = matchcount + 1
  10. print "The Match count is INSIDE THE LOOP: " + str(matchcount)
  11. ## counter2 = counter2 + 1 Has no effect
  12. else:
  13. print "counter1 & field NOT equal"
  14. ## counter1 = counter1 + 1 ## this statement does nothing
Note that the last statement is commented because it has no effect. Run the following code to see for yourself. This is because the statement "for ctr in range(0, 10)" generates a list [0, 1, 2...9] and iterates over this list so you increment the current value when incrementing the counter but don't change the list so there is no effect on the for() loop.
  1. for ctr in range(0, 10):
  2. print "loop's counter =", ctr
  3. ctr += 5
  4. print " ", ctr, "= incremented but doesn't have any effect"
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 15
Reputation: thanatosys is an unknown quantity at this point 
Solved Threads: 1
thanatosys thanatosys is offline Offline
Newbie Poster

Re: Absurd Loop Problem

 
0
  #3
Nov 20th, 2008
Thanks for that. I was able to resolve the issue. I will be posting the solution to this problem a bit later(deadline is pressing at the moment)
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC