Search code examples
pythonpython-3.xlistlogicsequence

Inserting sum of items of list while iterating through it


I've been trying to generate a sequence like this

1 2 1
1 3 2 3 1
1 4 3 5 2 5 3 4 1

The sequence basically inserts the sum of 2 consecutive list elements between them. Here's my solution:

a =[1,1]
h=[]
for j in range(1,5):
    h=a
    for i in range(0,len(h),2):
        h.insert(i+1, a[i]+a[i+1])
    print(a)
    a=h       

But it's somehow generating half right sequence after 3rd iteration.

[1, 2, 1]
[1, 3, 2, 3, 1]
[1, 4, 3, 5, 2, 5, 3, 1]
[1, 5, 4, 7, 3, 8, 5, 7, 2, 5, 3, 1]
[1, 5, 4, 7, 3, 8, 5, 7, 2, 5, 3, 1]

Can anyone help with what I did wrong. Thanks in advance


Solution

  • List's are handles. If you change one the other changes as well. Here is my suggestion.

    a =[1,1]
    h=[]
    for j in range(1,5):
        h=a.copy()
        for i in range(0,len(a)-1,1):
            h.insert(2*i+1, a[i]+a[i+1])
        print(a)
        a=h.copy()