Raily Krevch2021-03-04 16:57:32
Raily Krevch, 2021-03-04 16:57:32

After every 5th element, insert an element that is equal to the sum of these 5 elements?

a = [1,2,23,4,5,6,7,40,9,10,100,12,13,14,15,700,17,18,19,20]

for i in range(0, len(a), 5):

a = [1,2,23,4,5,6,7,40,9,10,100,12,13,14,15,700,17,18,19,20]
i = 5
while i < len(a):
    a.insert(i, 33333335)
    i += 6
print (a)

I found the amount and understood how to insert it, but the amount after every 5 will be different (not everywhere 35 ..), how can this be done? So that after every 5 they display their sum.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Andrey Dugin, 2021-03-04

def generate(sequence, group_by=5, func=sum):
    for group in zip(*[iter(sequence)]*group_by):
        yield from group
        yield func(group)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question