Looping bug with a condition inside

Viewed 61

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.

6 Answers

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)

You don'tt need to do value = walls[wall], wall represents an element in the list and it is not an index.

for wall in walls:
    if wall > max_height:
        max_height = wall
return max_height     
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:
        if wall > max_height:
            max_height = value
    return max_height  

You dont need to write the index, as you loop for each elements. wall will be 0,1,0,....,0,2 in each iteration, so no need to write it as an index

There is a built-in function max().

print(max(walls))

It seems you are trying to get a max value from the list. Instead of using your function try use just that which will return your max value from walls list

walls = [0, 1, 0, 2, 1, 0, 3, 2, 1, 1, 1, 5, 0, 2]
print (max(walls))

this will print:

5
for wall in walls:

The wall in above line takes element of the list when iterate. So if you want it to behave as index value of the list you should use it as

for wall, ele in enumerate(walls):

By using enumerate you can get index value in wall and each element in ele. And using your code with enumerate it works fine.

Related