Python初学者,运行2.7
我想在Python中定义一个函数,比如N(d),递归地;具有以下属性:它对乘积a * b * N(a)N(b)求和,对于a和b整数大于或等于0,a + b = d,d是变量。感谢。
加
N(1)= N(2)= 1
答案 0 :(得分:4)
通过memoization在递归中表现出色。
def N(d, memoize = dict()):
if d == 1 or d == 2: return 1
if d in memoize: return memoize[d]
result = 0
for i in xrange(1, d):
result += (d - i) * (i) * N(d - i) * N(i)
memoize[d] = result
return result
print N(1000)
或者,以更简洁的方式,
def N(d, memo={1:1, 2:1}):
# http://oeis.org/A112915
if d not in memo:
memo[d] = sum(i * (d - i) * N(i) * N(d - i) for i in range(1, d))
return memo[d]
答案 1 :(得分:1)
def N(d):
if d == 1:
return 1
if d == 2:
return 1
sum = 0
for i in range(1,d):
tmp1 = N(i)
tmp2 = N(d-i)
sum += i*(d-i)*tmp1*tmp2
return sum
print N(5)