Reputation: 53
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
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
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
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
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
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
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