超出了查找黑桃王牌的最大递归深度



问题给出一副52张牌,找到黑桃王牌。计算机随机选择一张卡。可以重复选择同一张卡。

此搜索的最佳情况是 1,最坏情况是无穷大。 要找到黑桃王牌,您必须看到的平均卡牌数量是多少?

结果应为 52。我对该问题的代码如下,但在使用递归进行修改时收到错误消息。"运行时错误:超出最大递归深度"。你能建议吗?

# solve by recursion
def to_infinity():
index=0
while 1:
yield index
index += 1
result = 0 
for n in to_infinity():
"""
calculate the expected average number of cards 
"""
def prob(n):
"""
:param n: the nth card being draw
:return: the probability that the nth card is ace of spades
"""
if n == 1:
return 1.0 / 52
else:
p = 1 - (1.0 / 52)
return prob(n-1) * p
average = prob(n) * n
result += average
if n > 10000: break
print(result)

# not solve by recursion
def to_infinity():
index=0
while 1:
yield index
index += 1
result = 0 
for n in to_infinity():
"""
calculate the expected average number of cards 
"""
p = ((1 - (1.0 / 52)) ** (n - 1)) * (1.0 / 52)
average = p * n
result += average
if n > 10000: break
print(result)

修订的代码。调整了递归限制和边界条件。它现在有效。

import sys
sys.setrecursionlimit(10000) 
import itertools
import time
start_time = time.time()
result = 0
for n in itertools.count():
"""
calculate the expected average number of cards 
"""
def prob(n):
"""
:param n: the nth card being draw
:return: the probability that the nth card is ace of spades
"""
if n == 0:
return 0
if n == 1:
return 1.0 / 52
else:
p = 1 - (1.0 / 52)
return prob(n-1) * p
average = prob(n) * n
result += average
if n > 9000: break
print(result)
print("--- %s seconds ---" % (time.time() - start_time))

最新更新