I am writing a simple Python program. It's supposed to read two sorted lists from tab-delineated file and merge them into a single sorted list. The algorithm isn't too tough but Python seems to be ignoring the conditions in my loops and if statements!
Here's my input file:
1 2 3 10
7 9 100
Here's the relevant bit of code with print commands for debugging:
print 'list1 len =' + str(len(list1)) + ', list2 len = ' + str(len(list2))
while (i < len(list1)) or (j < len(list2)):
print 'i = ' + str(i)
print 'list1[i] = ' + str(list1[i])
if (list1[i] < list2[j]):
print str(list1[i]) + ' < ' + str(list2[j])
output.append(list1[i])
i += 1
else:
output.append(list2[j])
j += 1
The program reads in the correct values but seems to always read the if-condition as true at every iteration.
list1 len =4, list2 len = 3
i = 0
list1[i] = 1
1 < 7
i = 1
list1[i] = 2
2 < 7
i = 2
list1[i] = 3
3 < 7
i = 3
list1[i] = 10
10 < 7
i = 4
Traceback (most recent call last):
File "q2.py", line 22, in <module>
print 'list1[i] = ' + str(list1[i])
IndexError: list index out of range
Not only is the if-statement not working (10 < 7 isn't right!), it's also failing at the while loop, since 'i' gets to 4, the size of list1. What is happening?!
Thanks!!!!
Aucun commentaire:
Enregistrer un commentaire