Learner
Learner

Reputation: 53

Getting the sum of the first 2 elements in a list and insert it at the beginning - Python

Let's say I have a list [1,2,3,4], what I want is get the sum of the first 2 pairs and print them in this manner:

[1,2,3,4]
[3,3,4]
[6,4]
[10]

Basically, it should just keep on adding the first 2 elements of the list then delete the first 2 elements and insert the sum at the beginning until the list contains just 1 element. However I'm not able to print the same but just get this:

[1,2,3,4]
[3,3,4]
[3,4]
[3]

Here's my code for that:

counter = len(num_arr)

while (counter > 1):
    valHold = (sum(num_arr[:2]))
    del numArr[:2]
    numArr.reverse()
    numArr.append(valHold)
    numArr.reverse()
    print (numArr)
    counter -= 1

I'm really confused on what to do. Thank you very much!

Upvotes: 2

Views: 553

Answers (7)

B. M.
B. M.

Reputation: 18628

l=[1,2,3,4]
cumsum = 0
for i in range(len(l)):
    cumsum += l[i]
    print([cumsum]+l[i+1:]) 

Upvotes: 0

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

recursive solution:

l = [1,2,3,4]
def f(l):
    print(l)
    if len(l) < 2:
        return l
    return  f([sum(l[:2])] + l[2:])

Upvotes: 0

Hafees Kazhunkil
Hafees Kazhunkil

Reputation: 113

a=[1,2,3,4]
counter = len(a)
while (counter > 1):
    valHold = (sum(a[:2]))
    del a[:2]
    a.insert(0,valHold)
    print a
    counter = counter - 1

Upvotes: 0

dokelung
dokelung

Reputation: 216

Using recursive is another way:

l = [1,2,3,4]

def func(l):
    print(l)
    if len(l)==1:
        return True
    new_l = [l[0]+l[1]]
    new_l.extend(l[2:])
    return func(new_l)

func(l)

Upvotes: 0

Daniel
Daniel

Reputation: 42748

Just use slice replacement:

num_arr = [1,2,3,4]
while len(num_arr) >= 2:
    num_arr[:2] = [sum(num_arr[:2])]
    print(num_arr)

Upvotes: 3

varesa
varesa

Reputation: 2419

As @niemmi said in the comments, your code runs fine after you fix the variable names. It does not run at all the way you've posted it.

# test.py

num_arr = [1, 2, 3, 4]
print(num_arr)

counter = len(num_arr)

while (counter > 1):
    valHold = (sum(num_arr[:2]))
    del num_arr[:2]
    num_arr.reverse()
    num_arr.append(valHold)
    num_arr.reverse()
    print (num_arr)
    counter -= 1

$ python test.py
[1, 2, 3, 4]
[3, 3, 4]
[6, 4]
[10]

Upvotes: 2

alecxe
alecxe

Reputation: 473803

You can loop while the length of the list is more than 1 and use slicing:

l = [1, 2, 3, 4]
while len(l) > 1:
    l = [l[0] + l[1]] + l[2:]
    print(l)

Prints:

[3, 3, 4]
[6, 4]
[10]

Upvotes: 3

Related Questions