Reputation:
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]
P.S. when I try
d.pop()
After the assignment block it gives even stranger results.
Upvotes: 3
Views: 1627
Reputation: 402263
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]
Upvotes: 4