It is necessary that the program adds the values of the previous and next values of the number in the list.
For example, given the number of rad: 1 5 8 2
For the element [1] (5) the answer is 9 - add 1 and 8
Ps. There are no problems with extreme elements: "For list elements that are extreme, one of the neighbors is considered to be an element located at the opposite end of this list"
|
2 answers
If I understand the question correctly, the problem is solved as follows:
a=[1,4,5,8,22,34] for elem in range(len(a)): print(a[elem-1]+a[(elem+1)%len(a)]) Result:
38 6 12 27 42 23 |
Python encourages the use of not an index, but a declarative way of manipulating lists. In this case, he is not so beautiful than usual.
from itertools import cycle, islice arr = [1, 5, 8, 2] for a, b in zip(arr, islice(cycle(arr), 2, None)): print(f'{a} + {b} = {a+b}') 1 + 8 = 9
5 + 2 = 7
8 + 1 = 9
2 + 5 = 7
If you need to know the element for which neighbors are looking for, then you can:
arr = [1, 5, 8, 2] length = len(arr) arr3 = arr * 3 for n, a, b in zip(arr, arr3[length-1:], arr3[length+1:]): print(f'{n}: {a} + {b} = {a+b}') 1: 2 + 5 = 7
5: 1 + 8 = 9
8: 5 + 2 = 7
2: 8 + 1 = 9
|