0

I have 2 lists:
a=[0,1,5,7]
b=[2,10,6,3]

I need to get this list :

c=[(b[0]+a[0]),(b[0]+b[1]),(b[0]+b[1]+b[2]),(b[0]+b[1]+b[2]+b[3])]

I tried doing this using a for loop:

c=[(b[0]+a[0])]
for i in range(0,(len(b)-1)):
    for p in range(i+1,len(b)):
        if i==0:
            c.append((b[i]+b[p]))
            
        else:
            c.append((c[i]+b[p]))

I am supposed to get [2,12,18,21] but I am getting [2, 12, 12, 12, 18, 15, 15]

Where am I going wrong in the for loops?

Thank you :)

Edited by bharatk: corrected typo

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by bharatk
1

I would do it like this with list comprehension

Little funny sequence as it includes only one element from a in formula.

>>> b[:2]
[2, 10]
>>> c=[a[0]+b[0]]
>>> c.extend([sum(b[:x]) for x in range(2,len(b)+1)])
>>> c
[2, 12, 18, 21]
>>>

Edited by pyTony: n/a

0

Thank you tonyjv!!
It worked perfectly.
I guess I should maximize using Python idioms where ever possible...makes it simpler.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.