编码西尔维斯特序列

时间:2016-04-25 10:40:20

标签: python recursion sylvester

我需要在Python中编写Sylvester序列。序列的公式定义为

$$s_n = 1 + \prod_ {
  i = 0
} ^ {
  n - 1
}
s_i$$

$s_0 = 2$

但是,我在Python中编写此代码时遇到了太多麻烦。有人有关于如何做的建议吗?

1 个答案:

答案 0 :(得分:2)

Python中的简单递归解决方案:

def sylvelster(n):
    product = 1
    for k in range(n):
        product *= sylvelster(k)
    return product + 1

或者你可以选择一直流行的复杂外观:

from functools import reduce
from operator import mul

def sylvelster(n):
    return 1 + reduce(mul, map(sylvelster, range(n)), 1)

或者是迭代解决方案(使用显式堆栈)而不是递归解决方案(使用隐式堆栈):

from functools import reduce
from operator import mul

def sylvelster(n):
    products = [2]
    for k in range(n):
        products.append(1 + reduce(mul, products, 1))
    return products[-1]