I've written an algorithm that scans through a file of "ID's" and compares that value with the value of an integer i (I've converted the integer to a string for comparison, and i've trimmed the "\n" prefix from the line). The algorithm compares these values for each line in the file (each ID). If they are equal, the algorithm increases i by 1 and uses reccurtion with the new value of i. If the value doesnt equal, it compares it to the next line in the file. It does this until it has a value for i that isn't in the file, then returns that value for use as the ID of the next record.
My issue is i have a file of ID's that list 1,3,2 as i removed a record with ID 2, then created a new record. This shows the algorithm to be working correctly, as it gave the new record the ID of 2 which was previously removed. However, when i then create a new record, the next ID is 3, resulting in my ID list reading:
1,3,2,3 instead of
1,3,2,4. Bellow is my algorithm, with the results of the
print() command. I can see where its going wrong but can't work out why. Any ideas?
def _getAvailableID(iD): i = iD f = open(IDFileName,"r") lines = f.readlines() for line in lines: print("%s,%s,%s"%("i=" + str(i), "ID=" + line[:-1], (str(i) == line[:-1]))) if str(i) == line[:-1]: i += 1 f.close() _getAvailableID(i) return str(i)
Output: (The output for when the algorithm was run for finding an appropriate ID for the record that should have ID of 4):
i=1,ID=1,True i=2,ID=1,False i=2,ID=3,False i=2,ID=2,True i=3,ID=1,False i=3,ID=3,True i=4,ID=1,False i=4,ID=3,False i=4,ID=2,False i=4,ID=2,False i=2,ID=3,False i=2,ID=2,True i=3,ID=1,False i=3,ID=3,True i=4,ID=1,False i=4,ID=3,False i=4,ID=2,False i=4,ID=2,False