Looping bug with a condition inside

I am trying to loop a list and store de max value on a variable, but when I debugging I found a bug which don’t store the maximum well.

walls = [0, 1, 0, 2, 1, 0, 3, 2, 1, 1, 1, 5, 0, 2]

def snow_stored_cuadratic(walls):
    max_height = 0

    for wall in walls:
        value = walls[wall]
        if value > max_height:
            max_height = value
    return max_height     

When I go to the 4th value, which is 2 and I have store on my variable value the value of 1, the If statement to compare value > max_height gets stuck with the number 2.

Answer

Please note, that wall is not an index, it is an element of your list.

instead of value and this expression:

value = walls[wall]

just use wall

Moreover, use of the loop is not necessary, you can use max() function.

max_height = max(walls)

Leave a Reply

Your email address will not be published. Required fields are marked *