简体   繁体   中英

How to find the smallest number in each line of numbers? Without using min()

So I need to find the smallest number for each row in this file which contains these numbers:

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

How would I be able to sort through each row to find the smallest number without using the built in min() or importing anything? This is what I have so far:

for line in input_file:
    lines = line.split(' ')
    lines = line.replace('\n',"").replace(',',"")

    for i in range(len(lines)):
        total = int(lines[i])

        print total
        if total > maximum:
            maximum = total
            print 'hey', maximum
print 'HI', maximum

I don't use python, but here is general aproach:

for line in input_file:
    numbers = line.replace('\n',"").split(',')

    min = int(numbers[0])
    for num in numbers:
        n = int(num)
        if n < min:
            min = n
    print min

this will print minimal value for each row

Python Function

Python has a min() function built in:

min([7,5,3,4])

=> 3

Sort

This isn't recommended, but you could sort a list and then pick the first number. This is more computationally intensive, but doesn't use the min() function, if you want this for some reason. But really, the only reason you should use this is if you get a assignment for a class or something.

list = [7,5,3,4]
list.sort()
list[0] #=> 3

Yourself

If you need to implement this yourself, the following should work:

for line in input_file:
    numbers = [int(i) for i in line.replace('\n',"").split(',')]
    min = numbers[0]
    for num in numbers:
        if num < min:
            min = num
    print min

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM