我正在研究这个函数,在函数中我希望计算函数本身的迭代次数/递归次数。任何和所有帮助都会有所帮助!谢谢!
def runGenerations( L ):
""" runGenerations keeps running evolve...
"""
count = 0
show(L)
print(L)
time.sleep(0.05)
if allOnes(L) == True:
return L
else:
newL = evolve( L )
return runGenerations( newL ) + 1
答案 0 :(得分:3)
您可以在递归链上传递count
个参数:
def runGenerations(L, count=1):
show(L)
print(L)
if allOnes(L):
print("result found after {} attempts".format(count))
return L
newL = evolve(L)
return runGeneratons(newL, count+1) + 1
这个程序确实不需要递归。迭代解决方案将是:
def runGenerations_iterative(L):
count = 1
show(L)
print(L)
while not allOnes(L):
L = evolve(L)
count += 1
show(L)
print(L)
print("result {} found after {} attempts".format(L, count))
return L + count - 1
答案 1 :(得分:0)
我想我明白了!
def runGenerations( L ):
""" runGenerations keeps running evolve...
"""
count = 0
show(L)
print(L)
time.sleep(0.05)
if allOnes(L) == True:
return 0
else:
newL = evolve( L )
return 1 + runGenerations( newL )