为了理解递归的教育目的,我想解决以下问题:给定一个整数列表( foo
),其中保证0
,我想从该列表中随机选择一个数字,直到随机生成器选择0
,或者直到它运行100
时间为止。
反过来说,我的解决方案如下所示:
def num_random(foo):
nums = 0
x = math.inf
while nums < 100 and x != 0:
x = random.choice(foo)
nums += 1
return nums
相同函数的递归版本如下:
def count_random(foo, number):
x = random.choice(foo)
print("x = {0}".format(x)) # debug purposes
if x != 0 and number < 100:
count_random(foo, number + 1)
else:
return number
初步呼叫:
print(count_random([0, 1, 2, 3, 4, 5], 0))
递归解决方案的问题是,它总是返回None
,我不明白为什么。我的推理是:如果选择的整数不是0
,我们知道下一次调用中的整数数将是当前调用中的整数数加1。如果随机选择的整数是0
,则需要返回外部范围内的整数数。但是,我的函数总是返回None
。
为什么我的函数总是返回None
,以及如何修复它?
发布于 2021-01-31 06:46:04
在递归调用中缺少了return
语句:
def count_random(foo, number):
x = random.choice(foo)
print("x = {0}".format(x)) # debug purposes
if x != 0 and number < 100:
return count_random(foo, number + 1)
else:
return number
https://stackoverflow.com/questions/65976442
复制相似问题