Search code examples
pythonlistmultiplicationaccumulate

Cumulative product of a list


I have implemented a list of all prime numbers from a set amount. What I'm trying to do is hard to explain so I'll just show it with some hard code:

euclst = []
euclst.append((primelst[0]) + 1)
euclst.append((primelst[0] * primelst[1]) + 1)
euclst.append((primelst[0] * primelst[1] * primelst[2]) + 1)
....

So essentially I'm trying to take a single element in order from my prev list and multiplying it exponentially I guess and appending it to my other list.

I realized that I could just do this, which is probably easier:

euclst = []
euclst.append(primelst[0])
euclst.append(primelst[0] * primelst[1])
euclst.append(primelst[0] * primelst[1] * primelst[2])
....
#then add one to each element in the list later

I need some ideas to do this in a loop of some sort.


Solution

  • You want a list of the cumulative product. Here's a simple recipe:

    >>> primelist =  [2, 3, 5, 7, 11, 13, 17, 19, 23]
    >>> euclist = []
    >>> current = 1
    >>> for p in primelist:
    ...     current *= p
    ...     euclist.append(current)
    ...
    >>> euclist
    [2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870]
    >>>
    

    Another way, using itertools:

    >>> import itertools
    >>> import operator
    >>> list(itertools.accumulate(primelist, operator.mul))
    [2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870]
    >>>
    

    OR, perhaps this is what you mean:

    >>> [x + 1 for x in itertools.accumulate(primelist, operator.mul)]
    [3, 7, 31, 211, 2311, 30031, 510511, 9699691, 223092871]
    

    With the equivalent for-loop:

    >>> euclist = []
    >>> current = 1
    >>> for p in primelist:
    ...     current = current*p
    ...     euclist.append(current + 1)
    ...
    >>> euclist
    [3, 7, 31, 211, 2311, 30031, 510511, 9699691, 223092871]
    >>>