My code is not sorting?

84 views Asked by At

I have to create a program that will: open a file that consists of different sets of three numbers, and then output the smallest number for each line. (Note: I have to do it without using the min() function!)

For example if the file says:

6,3,5
4,4,8
3,7,2
1,8,9
9,0,6

It should print:

3
4
2 
1
0

My code:

def smallest(*lowest):
    small_numbers = [lowest]
    small_numbers.sort()

def main():
    input_file = open("datanums.txt", "r")
    number_file = input_file.readlines()
    smallest(number_file)
    for i in range(len(number_file)):
        print number_file[i][0]
main()

When I run it, it appears to be printing the first number for each line in the file instead of printing the lowest number in the file. How can I fix this?

1

There are 1 answers

0
brandonscript On BEST ANSWER

There are some changes needed, hopefully you can sort through this working example and see what I've done:

def smallest(numbers):
    newlist = numbers.split(',') #splits the incoming comma-separated array
    newlist.sort() #sorts alphabetically/numerical
    return newlist[0] #returns the first value in the list, now the lowest

def main():
    input_file = open("num.txt", "r")
    number_file = input_file.readlines()
    for i in range(len(number_file)):
        print smallest(number_file[i]).rstrip() #rstrip strips \n from output
main()