Cumulative product of a list

喜你入骨 提交于 2020-07-01 16:13:31

问题


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.


回答1:


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]
>>>



回答2:


You could do it like this:

euclst = [primelst[0]]
for p in primelst[1:]:
    euclst.append(euclst[-1]*p)
  • initialize your list with first element
  • loop and append the current element with the previous appended element

(since current result depends on previous results, it's not easily doable in a list comprehension)

To solve the more complex one with a +1 on it:

euclst = [primelst[0]+1]
for p in primelst[1:]:
    euclst.append((euclst[-1]-1)*p+1)

(the previous result is the product plus one, so to reuse it, just substract one)

EDIT: other answers make me realize that I'm overcomplicating things. A temp variable to store the cumulative product would probably be cleaner.




回答3:


It might be clearest to use an intermediate variable to keep track of the product, and then add the 1 as you put it in the list.

euclst = []
running_prod = 1
for p in primelst[]:
    running_prod *= p
    euclst.append(running_prod + 1)



回答4:


you can use something like this:

euclst.append(primelst[0])
euclst.append(euclst[-1]*primelst[i])


来源:https://stackoverflow.com/questions/41784149/cumulative-product-of-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!