Python 'if' And 'while' Conditions Not Working
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 Py
Solution 1:
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.
Post a Comment for "Python 'if' And 'while' Conditions Not Working"