要使用二项式系数计算加泰罗尼亚数,您首先需要编写一个计算二项式系数的函数。
def binomialCoefficient(n, k): # To optimize calculation of C(n, k) if (k > n - k): k = n - k coeff = 1 for i in range(k): coeff *= (n - i) coeff /= (i + 1) return coeff def catalan(n): return binomialCoefficient(2*n, n) / (n + 1) for i in range (11): print (catalan(i))
输出结果
这将给出输出-
1.0 1.0 2.0 5.0 14.0 42.0 132.0 429.0 1430.0 4862.0 16796.0