首页 > 解决方案 > Python中的累积积

问题描述

我正在尝试编写一个算法来给我这样的累积产品A=[1, 3, 5, 6, 8]cumprodA = [1, 3, 15, 90, 720]. 我认为对于经验丰富的统计学家来说这并不难,但我的编程技能有点薄弱。

标签: python

解决方案


Start with your multiplicative identity (1), and multiply it by each number, remembering the result and appending to a cumprod list while you do so.

def cumprod(lst):
    results = []
    cur = 1
    for n in lst:
        cur *= n
        results.append(cur)
    return results

Note that this is the general solution for any Monoidal operation. Start with the mzero and do the same steps. Cumulative sum starts with 0, Cumulative list extends starts with [], etc.


推荐阅读