0

我目前正在尝试对阶乘的递归进行计时,但我找不到在每个递归步骤中打印每个阶乘的方法。现在我已经尝试在 return 语句中打印它,这可以解决我的问题,但结果只是一堆乱七八糟的文字墙,时间碎片化了。

编辑:我应该提一下,我正在尝试获取整个过程的累积时间,而不是像下面打印语句那样的碎片化结果。

我试过类似的东西:

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
4

2 回答 2

1

修复缩进和微小(外观)更改后,它似乎工作正常:

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) + '! =', FactResult, '- Runtime = %.9f seconds' % (end-start))
        return FactResult

factorial(10)

它为我打印...而不打印结果值:

c:\tmp\___python\BobDunakey\so12828669>py a.py
1! - Runtime = 0.000001440 seconds
2! - Runtime = 0.000288474 seconds
3! - Runtime = 0.000484790 seconds
4! - Runtime = 0.000690225 seconds
5! - Runtime = 0.000895181 seconds
6! - Runtime = 0.001097736 seconds
7! - Runtime = 0.001294052 seconds
8! - Runtime = 0.001487008 seconds
9! - Runtime = 0.001683804 seconds
10! - Runtime = 0.001884920 seconds

...并打印值:

c:\tmp\___python\BobDunakey\so12828669>py a.py
1! = 1 - Runtime = 0.000001440 seconds
2! = 2 - Runtime = 0.001313252 seconds
3! = 6 - Runtime = 0.002450827 seconds
4! = 24 - Runtime = 0.003409847 seconds
5! = 120 - Runtime = 0.004300708 seconds
6! = 720 - Runtime = 0.005694598 seconds
7! = 5040 - Runtime = 0.006678577 seconds
8! = 40320 - Runtime = 0.007579038 seconds
9! = 362880 - Runtime = 0.008463659 seconds
10! = 3628800 - Runtime = 0.009994826 seconds

编辑

对于累积时间,您必须在通话之外进行测量。否则,您将无法捕获开始时间。它也更自然:

import time

def factorial(n):
    """Factorial function that uses recursion and returns factorial of number given."""

    if n < 1:
        return 1
    else:
        return n * factorial(n - 1)


n = 10

start = time.clock()
result = factorial(n)
end = time.clock()

print(str(n) + '! =', result, '- Runtime = %.9f seconds' % (end-start))

它打印:

c:\tmp\___python\BobDunakey\so12828669>py a.py
10! = 3628800 - Runtime = 0.000007200 seconds
于 2012-10-11T08:42:05.960 回答
0

将“end = time.clock()”和 print 语句移到捕获 n<1 的块中的“return 1”之前。这是递归堆栈最大深度的最后一次执行,因此您将错过的只是备份它。为了得到最合适的结果,您应该遵循 NullUserException 的建议和递归方法之外的时间。

于 2012-10-10T23:37:02.217 回答