problem with list in python

2

The exercise asks me to store 5 numbers read in a list and to show the POSITIONS of the largest number, but I do not know how to do it, because if the higher number is repeated 1 time, the program works for me, but if it is repeated several times, I do not know how to show me all the positions where it is repeated. This is my code:

try:

    lista=[]
    pos=1

    for i in range(5):
        numero=int(input("Digite un numero entero: "))
        lista.append(numero)

    print("El mayor numero esta en las posiciones:")
    mayor=lista[0]

    for l in range(len(lista)):
        if lista[l] > mayor:
            mayor=lista[l]
            pos+=1
    print(pos)  

except ValueError:
    print("El valor digitado debe ser numerico")
    
asked by Andress115 30.09.2018 в 06:27
source

2 answers

4

The issue is that you have two problems that can not be resolved in the same interaction:

  • Know which is the greatest
  • Know the positions of it

The higher value will only be known if you go through the complete list, which means that we must do a first cycle to find the largest and a second cycle to obtain the positions of this one. Also, as you can have several occurrences of the higher value, this should be handled in a new list mayores .

lista = [5,3,7,9,2,3,9,0]
mayor = lista[0]

# Buscamos el mayor
for l in range(len(lista)):
  if lista[l] > mayor:
    mayor=lista[l]

# Obtenemos las posiciones del mismo
mayores = []
for l in range(len(lista)):
  if lista[l] == mayor:
    mayores.append(l)

print(mayor)
print(mayores)

9
[3, 6]

Of course in Python there are many ways to solve this problem, this one in particular we could say is the most elementary and low level of abstraction, but we could also do something like this:

mayores = [i for i in range(len(lista)) if lista[i] == max(lista)]
print(mayores)
[3, 6]

In this case, we obtain all positions i of i for i in range(len(lista)) that comply with the value of the element equal to the maximum value if lista[i] == max(lista)

    
answered by 30.09.2018 в 17:39
2

If they can be several positions you have to store them in a list

pos = []

for l in range(len(lista)):
    if lista[l] > mayor:
        mayor=lista[l]
        pos= [l] 
    elif lista[l] == mayor:
        pos.append(l) 

If it is greater you store the value in a variable and r you start with the position "l", if the value is equal to the greater then you add the position to the list

    
answered by 30.09.2018 в 07:24