While Exercise for Proof

Asked

Viewed 440 times

1

I can’t do this exercise, not with while or with gone. If you can make it available to me the way it’s done with While and For,.

  1. Given a list of numbers, tell us the highest number on the list. Use the Len( ) function to find out the list size and the while repeat structure to scroll through the list.

Remembering that the program should be done exactly as requested in the exercise.

Code I managed to do, but super wrong:

lista = [0, 10, 20, 50, 80]
maior = lista[0]

while maior in lista < maior:
    print(maior)

1 answer

1


Well, I won’t get into the merit of how hard you must have tried or not to do this.

Basically, you need to go through all the elements of the list and check which one is the largest. This can be done in several ways.

What I did in my code was to make the variable i received a valid index (from lista), that is, it starts in 0 and goes up to len(lista) - 1. And then check if the element in this index is larger than the largest saved so far (in the variable maior)

lista = [0, 10, 20, 50, 80]

maior = lista[0]
i = 0
while i < len(lista):
    if lista[i] > maior:
        maior = lista[i]
    i += 1

print('O maior é {}'.format(maior))

See working on repl.it.

It is possible to do this without using any loop, with the function max()

maior = max(lista)
  • It worked, but why did the if look like this? And in the same row of the biggest = list[i]?

  • This is a ternary. It works like this, if the condition is met (maior < lista[i]), the variable maior receives the amount lista[i] otherwise, she gets the value maior (herself, in case).

  • I changed it to be clearer, @Pigot

  • Is there any way to do it other than by ternary? I edited my code above, it just prints the last, not the biggest ( what I edited)

  • I just switched to a normal if

  • What a code, @Pigot?

  • It worked, thank you very much! :)

  • A detail: it is good that you start maior with the first item on the list, because if the list has only negative numbers, zero will still be the largest - and there may not even be a zero on the list.

  • Thank you, @Andersoncarloswoss

  • Makes sense, haha, thank you!

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.