简体   繁体   中英

python summing elements in list: first + last, from last to first

I'd like to sum the the last element and first element in a list, then pop off the last element and set that value to the 2nd, 3rd, 4th to last elements to nth - 1 size. Looking something like this:

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

This is in the context of finding all the possible sums to a number. In the previous example they sum to 4. So far what I have is:

d = [1,1,1,1,1,1,1,1,1,1]
for x in range(1, len(d)+1):
    d[-x] = (sum(d[:1]) + d[-x])

Giving me this:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 2]
[1, 1, 1, 1, 1, 1, 1, 1, 2, 2]
[1, 1, 1, 1, 1, 1, 1, 2, 2, 2]
[1, 1, 1, 1, 1, 1, 2, 2, 2, 2]
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
[1, 1, 1, 1, 2, 2, 2, 2, 2, 2]
[1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
[1, 1, 2, 2, 2, 2, 2, 2, 2, 2]
[1, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

PS when I try

d.pop()

After the assignment block it gives even stranger results.

Your code should be removing two existing elements and adding a new one to your list. Or at least, remove the first element. I don't see you removing anything... just re-assigning.

Option 1
You can do this quite succinctly using pop + append :

while len(d) > 1:
     d.append(d.pop() + d.pop(0))
     print(d)

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

Option 2
Alternatively, with a single pop operation. This should be pretty efficient.

while len(d) > 1:
     d[-1] += d.pop(0)
     print(d)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM