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
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?!
解决方案
You want and, not or, in your while loop test:
while i < len(list1) and j < len(list2):
(i < len(list1)) or (j < len(list2)) is going to be true if one of those tests is true. So i doesn't have to be smaller than len(list1) as long as j is smaller than len(list2). False or True is still True.
Next, your if test is most likely comparing strings, not integers. Strings are compared lexicographically:
>>> 'abc' < 'abd'
True
>>> 'ab' < 'b'
True
>>> '10' < '2'
True
The first characters are compared before other characters are tested, and '1' sorts before '2'.
Compare integers instead:
if int(list1[i]) < int(list2[j]):
You probably want to convert your file inputs to integers the moment you read them, however.