The program must, for each element of this list, print the sum of its two neighbors. For list items that are extreme, one of the neighbors is considered to be an item located at the opposite end of this list. For example, if the input is a list of "1 3 5 6 10", then the output is expected to list "13 6 9 15 7" (without quotes). If only one number has come to the input, you must output it. The output should contain one line with the numbers of the new list, separated by a space.

count=[] nums=input() row = list(map(int, nums.split())) i=0 while i<=len(row): if len(row) == 1: print(row[0]) if i == 0: count.append(row[-1] + row[1]) if i == len(row): count.append(row[-2] + row[0]) if 0<i<len(row): count.append(row[i-1] + row[i+1]) i+=1 print(count) 

I can not understand why it gives an error about exceeding the boundaries. There is a similar question here, but I can not figure out the answers.

Reported as a duplicate by jfs , Cheg , andreymal , Pavel Mayorov , сСн 25 Sep '17 at 20:42 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Suppose a list has a length of 10, valid indices are from 0 to 9, and your cycle will be from 0 to 10 inclusive. - insolor
  • Here I blunted, tin. Thank you so much) - Dimitri

3 answers 3

My solution:

 def getSumElements(array): result = [] if len(array) == 1: return array for index, elem in enumerate(array): if index == 0: result.append(sum([array[-1], array[1]])) elif index == len(array)-1: result.append(sum([array[-2], array[0]])) else: result.append(sum([array[index - 1], array[index + 1]])) return result print(getSumElements([1, 2, 1, 3, 2])) # [4, 2, 5, 3, 4] 

To make your code work, subtract from each len(row) one.

Since len() returns the number of elements and not indices, for example:

 In [32]: array = [1, 2, 3] In [33]: len(array) Out[33]: 3 

as you can see, we got 3 , but our indexes are: 0, 1, 2 .

  • one
    Thank you very much) - Dimitri
  • does not work correctly, for example, for array=[1, 2, 1, 3, 2] , result == [4, 4, 4, 3, 4] , but it should be [4, 2, 5, 3, 4] - vadim vaduxa
  • @vadimvaduxa, thanks, corrected - Pavel Durmanov
  • sum([a, b]) can be written as a+b here. The case of index==0 already being processed by you, there is no need to take out a separate branch. To process i=len(L)-1 , you can (i+1) % len(L) use , then all if statements can be removed. For obviously small input, you can simplify and not count indices - jfs

speed

 import random, itertools, timeit def nums_by_iter(): '''способ с ΠΈΡ‚Π΅Ρ€Π°Ρ‚ΠΎΡ€Π°ΠΌΠΈ''' if len(array) > 1: def get_summ(): right = itertools.cycle(array) next(right); next(right) for left in array: yield left + next(right) *last, first = get_summ() return [first] + last return array def nums_by_index(): '''способ с индСксами''' ln = len(array) if ln > 1: return [array[i-1]+array[i+1] for i in range(ln-1)] + [array[-2]+array[0]] else: return array def getSumElements(): '''Π²Π°Ρ€ΠΈΠ°Π½Ρ‚ Alban''' ... if __name__ == '__main__': array = tuple(random.randrange(1000000) for _ in range(100)) for func in [nums_by_iter, nums_by_index, getSumElements, ]: print('{t} сСк - {n}'.format(t=round(timeit.Timer(func).timeit()), n=func.__name__)) 

out:

 30 сСк - nums_by_iter 33 сСк - nums_by_index 94 сСк - getSumElements 
     array = [1, 3, 5, 6, 10] ln = len(array) # способ с индСксами if ln > 1: result = ' '.join(str(array[i-1] + array[i+1]) for i in range(ln-1)) \ + ' %s' % (array[-2] + array[0]) else: result = str(array[0]) if array else '' print(result) # способ с ΠΈΡ‚Π΅Ρ€Π°Ρ‚ΠΎΡ€Π°ΠΌΠΈ import itertools def nums_by_iter(): r = itertools.cycle(array) next(r) right = next(r) left = array[-1] for l in array: yield str(left + right) left, right = l, next(r) if ln > 1: result = ' '.join(nums_by_iter()) else: result = next(iter(array), '') print(result)