2

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!

Learner
  • 53
  • 2
  • Why do you want to do that? Do you finally want to get `[10]` or is it an assignment where you have to go through the iterative process , modify the list and print it to understand its behavior? – AKS May 07 '16 at 14:01
  • 1
    Should `num_arr` and `numArr` be same or different variable? If you fix the name the code should behave pretty much as you expect... – niemmi May 07 '16 at 14:03

7 Answers7

3

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)
Daniel
  • 42,087
  • 4
  • 55
  • 81
2

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]
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

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]
varesa
  • 2,399
  • 7
  • 26
  • 45
  • Yes his code has some errors and should be fixed like you have answered. This [**online demo**](https://repl.it/COQl/0) – SaidbakR May 07 '16 at 14:13
0

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)
dokelung
  • 206
  • 1
  • 5
0
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
0

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:])
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
0
l=[1,2,3,4]
cumsum = 0
for i in range(len(l)):
    cumsum += l[i]
    print([cumsum]+l[i+1:]) 
B. M.
  • 18,243
  • 2
  • 35
  • 54