Error when using index to pick up a specific index

Asked

Viewed 84 times

0

I would like to take the position from where the highest entered value is within the list. I am trying with the index but am not getting.

for c in range(0, 5):
    num.append(int(input('Digite 5 valores: ')))
    if c < 1:
        maior += num[0]
        menor += num[0]

    for val in num:
        if val >= maior:
            posmaior += val.index()
            maior = 0
            maior += val

4 answers

1


From what I understand you are wanting to implement a code that is able to assemble a list with 5 values, check the highest value element and then specify the index of this value.

Well, when you do:

for c in range(0, 5):
    num.append(int(input('Digite 5 valores: ')))

The code captures the entered value and tries to insert into an object in a. This object, which should be defined earlier and which is of type list. Only you have not defined it previously. So such object - list - cannot be fed.

Another thing, Python already provides a function to calculate the maximum value of a list. In this case the function is max().

Also, for you to relate index with value you can use the function enumerate.

By paying attention to these observations you can implement the following code:

num = list()
for i in range(1, 6):
    num.append(int(input(f'Digite o {i}º valor: ')))

maior = max(num)

for indice, item in enumerate(num):
    if item == maior:
        print(f'O maior valor é {item} e possui índice {indice}')
        break

Note that the first for assemble a list of the 5 values passed. The second for will go through the list in a and will check the item whose index has higher value. And, if this item has the higher value it will display the respective item and index.

Also note that this code has a break. This will serve to interrupt the execution of the second for when he finds the maximum value item.

Now, if the list has more than one item of higher value, you can remove the break.

This way the code will be

num = list()
for i in range(1, 6):
    num.append(int(input(f'Digite o {i}º valor: ')))

maior = max(num)

for indice, item in enumerate(num):
    if item == maior:
        print(f'O maior valor é {item} e possui índice {indice}')

In the latter code we can list all the values of the list that may have greater value.


Now, if you want to capture all values from a single input(). You can implement the following code:

num = list(map(int, input('Digite os 5 valores: ').split()))

maior = max(num)
for indice, item in enumerate(num):
    if item == maior:
        print(f'O maior valor é {item} e possui índice {indice}')

Note that when we execute this code we receive the following message: Digite os 5 valores: . At this point we must type all the 5 values, in the same line, separated for a single space and press Enter.

From this moment the entered values will be mounted in the name list in a. Subsequently the highest value (max()) will be calculated and then the result is displayed.

1

Well, I tried running your code, but some error messages appeared. The "num" list is not defined, as well as other variables such as "major". I also believe that it might not be a good idea to add all the numbers at once without determining the creation of a second list or something like that.

Here’s a simple alternative for you.

num = []

print("Digite 5 valores.\n")

#Loop para que o usuário digite os 5 valores
z = 1
for i in range(5):
   n = int(input("Digite o valor " + str(z) + ": "))
   num.append(n)
   z += 1

num2 = sorted(num) '''Aqui, criei uma segunda lista, na qual adiciono os elementos da 
primeira lista e os organizo em ordem crescente com a função sorted(), de modo que o 
último elemento,
ou seja, o quarto (pois a lista é contada a partir do 0), será o maior.
'''

posição = num.index(num2[4]) '''Procurando último elemento da lista 2, que equivale ao 
maior da lista 1'''

#Exibindo o resultado
print("\nA posição do maior valor é a ", posição, ", mas, \
lembre-se de que a contagem dos elementos da lista começa a partir do 0, portanto, o 
maior elemento é o", posição + 1, "º.")

1

num = []                                          #Inicia a lista de coleta de dados.

print('Digite 5 valores.')
for c in range(1, 6):                             #Iterando em c pelos números de 1 a 5...
  while(True):                                    #...inicia um laço de coleta de dado...
    try:                                          #...inicia um bloco de tratamento de exceções... 
      num.append(int(input(f'nº{c}: ')))          #...coleta, converte e adiciona dado a lista.
      break;                                      #...se não ha erros abandona o laço.
    except ValueError:                            #...caso ha um erro permanece no laço.
      print("Valor inválido, digite novamente")

k = lambda t: t[1]                                #função que orientará min() e max() a o que comparar.
maior = max(enumerate(num),key=k)                 #Obtem o maior elemento de num junto do seu índice
menor = min(enumerate(num),key=k)                 #Obtem o menor elemento de num junto do seu índice.

print(f"Da lista {num}:")
print(f"* o maior elemento é o {maior[1]} no índice {maior[0]}")
print(f"* o menor elemento é o {menor[1]} no índice {menor[0]}")

Test the example on Ideone

Whenever you collect a data check whether this data is direct from the user, whether from a file, a pipe, from the internet,.... whatever the source of this data it probably needs to be treated before being worked within your program.
Your program will receive a user input via keyboard where your code has been designed to handle only whole numbers if the user provides input something other than an entire program stops working.

In critical situations, portions of code that can stop your program from working should be placed inside a block of exception handling whose python is defined by the statement Try/except.

As for the functioning of the code has no secrets it uses the built-in functions min() and max(), aided by k, to find the lowest and highest value within the list enumeration num.

Enumeration is obtained with the built-in function enumerate() that only returns a sequence of tuples (indice, valor) extracted from num.

The function k is an aid to min() and max() only compare the values of the enumeration.

0

As already stated by other users, with the use of max() , you find in a row the highest value within the list. It has also been mentioned the use of enumerate() as a way to iterate an array keeping the index. From there, it is possible to make a list comprehension of the enumerated list, searching the index of the highest value numbers. That way, the code goes like this:

nums = list()

for i in range(0, 5):
    nums.append(int(input(f'Insira o {i + 1}o número: ')))

'''
Aqui se define o maior valor para
que não seja repetida a função max
'''
maior_valor = max(nums)
maiores_index = [index for index, i in enumerate(nums) if i == maior_valor]

print(f'O(s) maior(es) número(s) da lista é(são) o(s) de index {maiores_index}')

If the use of list comprehension has confused you, you can also use a common loop, the code looks like this:

nums = list()

for i in range(0, 5):
    nums.append(int(input(f'Insira o {i + 1}o número: ')))

maior_valor = max(nums)
maiores_index = list()

for index, num in enumerate(nums):
    if num == maior_valor:
        maiores_index.append(index)

print(f'O(s) maior(es) número(s) da lista é(são) o(s) de index {maiores_index}')

Browser other questions tagged

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