D
D
Danila Belyy2021-11-01 00:34:50
Python
Danila Belyy, 2021-11-01 00:34:50

How to calculate the sum of adjacent elements in a list?

Write a program that takes a list of numbers as input in one line. The program must for each element of this list print the sum of its two neighbors. For list elements that are extreme, one of the neighbors is the element located at the opposite end of this list. For example, if the input is the list "1 3 5 6 10", then the output is expected to be the list "13 6 9 15 7" (without quotes).

If only one number came to the input, you need to output it.

The output should contain a single line with the numbers of the new list separated by a space.

spisok = [int(e) for e in input().split()]
long = len(spisok) -1
s1 = []
suma = 0
stroka = ""

if long == 0:
  print(spisok[0])

elif long == 1:
  print(spisok[1]*2, end=' ')
  print(spisok[0]*2, end=' ')
  
else:
  
  for i in spisok:
    
    if i == spisok[0]:
      suma = spisok[1]+ spisok[-1]
      s1.append(suma)
      i += 1
      suma = 0
      
    elif (i != spisok[0]) and (i != spisok [-1]):
      ind1 = spisok.index(i) -1
      ind2 = spisok.index(i) + 1
      suma = spisok[ind1] + spisok[ind2]
      s1.append(suma)
      i += 1
      suma = 0
      
    
    elif i == spisok[-1]:
     		suma = spisok[-2] + spisok[0]
     		s1.append(suma)
     		i += 1
     		suma = 0

for k in s1:
  stroka += str(k) + " "
print(stroka)

How can I change this code so that it works correctly when element values ​​are repeated (how can I get rid of using index())?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-11-01
@0xD34F

arr = [ int(n) for n in input().split() ]
arrLen = len(arr)
result = arr if arrLen == 1 else [ arr[i - 1] + arr[(i + 1) % arrLen] for i in range(arrLen) ]

print(' '.join(map(str, result)))

A
alexbprofit, 2021-11-01
@alexbprofit

e = [int(el) for el in input().split(" ")]

result = []

for i in range(len(e)):
  if i == 0:
    result.append(e[i] + e[-1])
  elif i == len(e) - 1:
    result.append(e[i-1] + e[0])
  else:
    result.append(e[i - 1] + e[i+1])
result = [str(el) for el in result]
print( ' '.join(result))

But still, the option that was given in the answer above is shorter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question