Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A nested loop that adds numbers from the sequence in pairs

I have a list:

the_list = [1, 2, 3, 4, 5]

Next I would like to sum pairs of numbers from the list, next pairs in the next step, and so on, until we get only one number at the end. The next steps would look like this:

 [3, 5, 7, 9]
 [8, 12, 16]
 [20, 28]
 [48]

I use a loop to add pairs:

the_list = [1, 2, 3, 4, 5]

for i in range(len(the_list) - 1):
    a, b = the_list[i], the_list[i + 1]
    c = a + b
    print (c)

What gives:

3
5
7
9

But I do not know how to loop it to the next steps. Because, for now, only a very bad idea of adding to the new list comes to mind, which would be a completely wrong idea with a large starting list. How can this be done?

like image 839
Tomasz Przemski Avatar asked Dec 03 '25 09:12

Tomasz Przemski


1 Answers

You can zip the list against itself offset by one index, then sum consecutive elements until the list collapses into a slngle value

l = [1, 2, 3, 4, 5]
while len(l) > 1:
    l = [i+j for i,j in zip(l, l[1:])]
    print(l)

Output

[3, 5, 7, 9]
[8, 12, 16]
[20, 28]
[48]
like image 81
Cory Kramer Avatar answered Dec 04 '25 21:12

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!