编码Sylvester序列

Coding Sylvester sequence

I need to code the Sylvester sequence in Python. The formula for the sequence is defined as

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

Where $s_0 = 2$.

However, I am having too much trouble writing this code in Python. Does anyone have a suggestion on how to do it?

A simple recursive solution in Python:

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

Or you could go for the always popular sophisticated looking one liner:

from functools import reduce
from operator import mul

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

Or an iterative solution (with explicit stack) instead of a recursive one (with implicit stack):

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]