Question: Given a list of integers, write python code to create a new list with the same number of elements as the original list such that each integer in the new list is the sum of its neighbors and itself in the original list. Example: is listA = [10,20,30,40,50], listB = [30,60,90,120,90]
I’m struggling with finding the right way to set up this code. I know how to define the function but how do you set up the adding of neighbor integers/itself? Any help would be appreciated.
What I have so far:
def sumNeighbors(list, start = 0, end =None):
if end is None:
end = len(list)
sum = 0
i = start
while i < end:
sum += list[i]
i += 1
return sum
text = raw_input ("Enter an integer (period to end): ")
list = []
while text != '.':
textInt = int(text)
list.append(textInt)
text = raw_input("Enter an integer (period to end): ")
print "List: ", list
print "sum: ", sumNeighbors(list)
I just special cased the ends of the list. Basically, at the start of the list, you only want add the right neighbor, and at the end of the list, you only want to add the left neighbor.
So, I start by appending the first item which is just the value at index 0 + the value at index 1.
new_list.append(list[0] + list[1])Then, I use a while loop to iterate through all the middle indexes.
For each of those, we are summing
list[x - 1] + list[x] + list[x + 1]Careful to start summing the middle with index 1, not 0, as 0 was already special cased. Then make sure you don’t go off the end, by using a for loop that goes to
len(list) - 1. For the last item, you just sumlist[x - 1] + list[x]Here’s the whole code: