Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent to clojure reductions

Tags:

python

In Clojure, we have a function like this

(reductions str ["foo" "bar" "quax"])
=> ["foo" "foobar" "foobarquax"]

or

(reductions + [1 2 3 4 5])
=> [1 3 6 10 15]

It's basically just reduce but it collects the intermediate results.

I'm having trouble finding an equivalent in Python. Does a base library function exist.

Python 3

like image 341
Stuart Avatar asked Aug 17 '20 13:08

Stuart


Video Answer


1 Answers

You can use itertools.accumulate

from itertools import accumulate

l = [1, 2, 3, 4, 5]

print([*accumulate(l)])

Prints:

[1, 3, 6, 10, 15]
like image 190
Andrej Kesely Avatar answered Oct 06 '22 06:10

Andrej Kesely