Home > Software design >  Why is this function not returning the correct number from the array
Why is this function not returning the correct number from the array

Time:05-02

This function is selecting -70 for the min as expected, but it is selecting 43 for the max when it should be selecting 54 as the max. Instead of getting 124 as expected, I am only getting 113. Any insight would be much appreciated.

def difference_max_min(lst):
    minn = lst[0]
    maxx = lst[0]
    for i in range(0, len(lst)):
        if lst[i] < minn:
            minn = lst[i]
        if lst[i] > maxx:
            maxx = lst[i]
            print(minn)
            print(maxx)
            return maxx - minn


print(difference_max_min([-70, 43, 34, 54, 22]))

I could probably do this easier by sorting the list and just taking the first and last indexes and subtracting them that way, but I can't for the life of me understand why this way is not working.

P.S. the prints are only in there because I was trying to troubleshoot the issue.

CodePudding user response:

Indentation issue:

def difference_max_min(lst):
    minn = lst[0]
    maxx = lst[0]
    for i in range(0, len(lst)):
        if lst[i] < minn:
            minn = lst[i]
        if lst[i] > maxx:
            maxx = lst[i]
    print(minn)
    print(maxx)
    return maxx - minn


print(difference_max_min([-70, 43, 34, 54, 22]))

Just to help a bit, try to run a debugger to go through the code. I would ask you to look into the pdb. This would be helpful in debugging these situations.

CodePudding user response:

Put the return statement outside the if statement. Otherwise you return the difference when your program finds an element that is bigger than maxx the first time.

  • Related