1

I'm searching for a method to use itertools.accumulate in starmap.

I tried to calculate the accumulated sum of each row in a table, then concatenate the results to an array:

# my input
my_table = [[3, 5], [1, 4, 7], [2]]
# expected output
P = [3, 8, 1, 5, 12, 2]

I use itertools in a for loop, but it becomes much slower than other ways. So is it possible to use starmap or other itertools method make it quicker?

def getSums(my_table):
    P = []
    for i in range(len(my_table)):
       P.append(itertools.accumulate(my_table[i]))
    P = itertools.chain.from_iterable(P)
    return P

3 Answers 3

3

You don't need starmap just use built-in map function and chain the result using itertools.chain():

In [47]: list(chain.from_iterable(map(accumulate, my_table)))
Out[47]: [3, 8, 1, 5, 12, 2]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I've tried your code and it works well.
1

You can use your initial loop approach in a much simplified version, using extend which can take any iterable:

P = []
for lst in my_table:
    P.extend(accumulate(lst))

Comments

1

Use Itertools works well, here is what happens under the hood, you can write your own solutions just use generators(no stdlib needed).

def chain_cumsum(table):
    for it in table:
        yield from cumsum(it)

# write a function to get accumulated sum
def cumsum(l):
    total = 0
    for i in l:
        total += i
        yield total

# then you can get your output:
list(chain_cumsum(my_table))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.