Reputation: 491
My ultimate goal is to sum a list of values by summing each pair in the list, producing a smaller list, summing each of those pairs, and so on. For now, I have a list with an even number of elements, but eventually I want to be able to handle an arbitrary sized list.
With some help from previous posts, I have this function:
def collapse_sum(lst):
sums = list()
rems = list()
acc = 0
n = 2
print(lst)
print("final sum: {}\n".format(sum(lst)))
pairs = [lst[i:i + n] for i in range(0, len(lst), n)]
while len(pairs) > 0:
if len(pairs) % 2 == 1:
rems.append(pairs[-1])
del pairs[-1]
for a,b in pairs:
sums.append(a + b)
pairs = [sums[i:i + 2] for i in range(0,len(sums),n)]
sums = list()
if len(pairs) == 1:
for a,b in pairs:
acc += a + b
rems = [item for sublist in rems for item in sublist]
pairs = [rems[i:i + n] for i in range(0, len(rems), n)]
if len(pairs) == 1:
for a,b in pairs:
acc += a + b
del pairs[-1]
return acc
rems = list()
print(acc)
return acc
Upvotes: 0
Views: 35
Reputation: 40888
My ultimate goal is to sum a list of values by summing each pair in the list, producing a smaller list, summing each of those pairs, and so on.
Here's a solution that does that for even or odd-sized lists, without using any library dependencies.
# Helper function to split iterable obj into blocks/chunks
def blocks(obj, n):
for i in range(0, len(obj), n):
yield obj[i:i + n]
def collapse_sum(obj):
while len(obj) > 1:
obj = blocks(obj, 2)
obj = [sum(i) for i in obj]
return obj[0]
Some examples:
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4]
collapse_sum(a)
15
collapse_sum(b)
10
You can visualize this here.
Upvotes: 1