Silentstorm Silentstorm - 1 year ago 69
Python Question

Python Section Sort does not function as it is told to do so

If I input a single digit number or numbers with the same first digit (10, 11, 12, 13), the code works perfectly. However, as soon as this condition is not met, the program thinks 7 is larger than 12...

Here is what I have tried.

def main():
mark = 0
file_name = input('Enter the name of the file: ')
lst = []
for num in open(file_name):
lst = sort(lst, mark)

def sort(lst, mark):
while mark <= len(lst) - 1:
minval = lst[mark]
for i in range(len(lst)):
if lst[i] > minval:
lst[i], lst[mark] = lst[mark], lst[i]
minval = lst[mark]
mark += 1
sort(lst, mark)
return lst


Answer Source

It sounds like you're sorting the numbers as strings instead of as integers. In fact, the string "7" is larger than the string "12" in the same way that the string "g" would come after the string "ab" in the dictionary.

You can avoid this by casting your inputs to ints:

num = int(input_string)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download