Home > database >  Why isn't my function for getting the smallest value from a list working
Why isn't my function for getting the smallest value from a list working

Time:02-20

I made a function for getting the smallest value from a list but it is not working properly and returning the wrong value. It prints out 5. What is wrong with it?

def finding_least_num(a_list):
    first = 0
    for i in a_list:
        while first < len(a_list)-1:
            if i < a_list[first]:
                min_num = a_list[first]
            first = first   1
        first = 0
    print(min_num)
finding_least_num([3,7,5,2,9])

CodePudding user response:

I am not sure why there are a lot of inner if and while statements. @Swishy has diagnosed the problem you are sticking with correctly. if you are insisting on not using min function, you can try code below:

def finding_least_num(a_list):
    first = float('inf')
    for value in a_list:
      if value < first:
        first = value
    return first

which results in 2 in the case of using [3,7,5,2,9] as an input for the function.

Note that float("inf") is referring to the maximum number available in python.

CodePudding user response:

if i < a_list[first]:

This is your problem, this instead needs to be:

if min_num > a_list[first]

It doesn't work because you are not checking against the lowest number you have saved already in min_num. You also need to initialize min_num to the first record in the array.

CodePudding user response:

def finding_least_num(a_list):
    first = 0
    for i in a_list:
        print("testing i = ", i)
        while first < len(a_list)-1:
            print("first = ", first)
            if i < a_list[first]:
                print ("checking if i < ", a_list[first])
                print("i", i)
                min_num = a_list[first]
                print("minimum number here is ", min_num)
           first = first   1
        first = 0
    print(min_num)
finding_least_num([3,7,5,2,9])

I rewrote your code with comments and run it. Copy this into your interpreter and you will see the error and the reason why you received 5 each time. You will realize that your first for loop takes the first index of the array you passed to the function and tests it against the second while loop (let's call it chosen index). For each cycle the selected index is tested if it is less than the chosen index. If true set the minimum number as the chosen index. If you test the new code I have up there with the prints you will discover the last minimum number recorded is what was returned after the two loops completed. Python has many methods to help in these instances. For example min() is a very good way to simplify things. Another good way is to sorted() the array and return the first or last index depending on the order of the sorting.

  • Related