我目前正在尝试对阶乘的递归进行计时,但我找不到在每个递归步骤中打印每个阶乘的方法。现在我试着把它打印在return语句中,这样就可以解决我的问题了,但结果只是一堆乱七八糟的文本,时间被分散了。你知道吗
编辑:我应该提到的是,我正在努力获得整个过程的累积计时,而不是像下面的print语句那样零碎的结果。你知道吗
我试过这样的方法:
return (str(n) + '! = ' + (str(FactResult)) +
' - Runtime = %.9f seconds' % (end-start))
但这是我现在所拥有的。你知道吗
import time
def factorial(n):
"""Factorial function that uses recursion and returns factorial of
number given."""
start = time.clock()
if n < 1:
return 1
else:
FactResult = n * factorial(n - 1)
end = time.clock()
print(str(n) + '! - Runtime = %.9f seconds' % (end-start))
return FactResult
在修复压痕和轻微(外观)变化后,它似乎可以正常工作:
它为我打印。。。不打印结果值:
。。。通过打印值:
编辑
对于累计计时,您必须在通话之外进行测量。否则您将无法捕获开始时间。更自然的是:
它打印:
移动“结束=时钟()”和捕捉n<;1的块中“return 1”前面的print语句。这是递归堆栈最大深度的最后一次执行,因此您将错过的只是备份。为了得到最正确的结果,应该遵循NullUserException的建议,并在递归方法之外使用time。你知道吗
相关问题 更多 >
编程相关推荐