Operations sum and multiplication of integer numbers in Python list

Asked

Viewed 335 times

0

The list code needs to receive 5 five numbers in reverse order, my code does it only that my code needs the 2nd number entered to be multiplied by 3 and the 4th number to be added by 5 (remembering that there is indexing by zero so it is element 0, 1, 2, 3 and 4).

This part is just an example of the desired answer:

Entrada = [5, 15, 25, 35, 45]
Saída = [50, 35, 25, 45, 5]

For now my code is like this (shows the inverted elements):

elements = input("Enter only 5 numbers: ")

list = elements.split()

inverse_list = list[::-1]

print (inverse_list)
  • You’re adding 5 to the 5th number.

  • But that’s exactly it, remember that the 5th number will be the 4th number and the 1st number will be the 0º number

  • Because of the very common zero indexing in programming languages, understand?

  • Remembering that the list will display the result in reverse order

  • 1

    And how you tried to multiply/add the values?

  • That’s the problem, I can’t select the element and add/multiply it.

Show 1 more comment

2 answers

2


Thus:

elements = input("Enter only 5 numbers: ")
list = elements.split()

# Acresente essa linha
list[1], list[4] = int(list[1])*3, int(list[4])+5

inverse_list = list[::-1]
print (inverse_list)

Output for the given example:

[50, '35', '25', 45, '5']
  • how it makes the result look like this [50, 35, 25, 45, 5] ?

  • Let me fix it, thanks for the explanation.

1

Did you study about arrays? Take a look here!

First thing you need to do is convert your list to int

results = list(map(int, elements.split(',')))

Then you can take the array values from the index. You can do this manually or dynamically.

results[1] = results[1] * 3
results[4] = results[4] + 5

Then you just flip.

inverse_list = results[::-1]

Resultado

  • Yes, but had seen arrays in C language

  • Thank you very much, it took me a while to understand because it started to make some mistakes, but I managed.

Browser other questions tagged

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