I have a task in the course which sounds like this: Write a program that takes as input a list of numbers in one line. The program should output the sum of its two neighbors for each element of this list. 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 the list "13 6 9 15 7" (without quotes). If only one number came to the input, you need to display it.
Sample Input 1: 1 3 5 6 10
Sample Output 1: 13 6 9 15 7
Problem occurs when i try to operate with the first number after checking if there is one number. It says 'int' object is not iterable. I tried to edit my code with various constructions with if, while, for. But it is all the same. Would you kindly help me to understand how to operate with integers in the list and add the results of the operations to the new one? Here is the code (result is the supposed output):
user_input = input()
lst = [int(i) for i in user_input.split(' ') if i.isdigit()]
result = []
if len(lst) == 1: #Check if one element
print(lst[0])
if len(lst) > 1:
for lst[0] in range(len(lst)): #For the first index
result = (lst[1] lst[-1])
CodePudding user response:
Following the code you've pasted, this is the way it should be completed:
user_input = '1 3 5 6 10'
lst = [int(i) for i in user_input.split(' ') if i.isdigit()]
result = []
if len(lst) == 1:
print(lst[0])
elif len(lst) == 2: # What happens if there are 2 elements?
print(lst[1], lst[0])
else:
for index in range(len(lst)): # range(n) returns a generator that yields [0, ..., n - 1]
result.append(lst[index - 1] lst[(index 1) % len(lst)])
# result.append(n) adds n to the "result" list
# lst[(index 1) % len(lst)] we need the modulo (%) because a list of n elements
# won't have an index n, thus you want the sum of elements n - 1 and 0 == n % n