0

現在、階乗の再帰の時間を計ろうとしていますが、各再帰ステップですべての階乗を印刷する方法が見つかりません。今、私の問題を解決する 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
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

n<1 をキャッチするブロックの「return 1」の直前に「end = time.clock()」と print ステートメントを移動します。これは再帰スタックの最大の深さでの最後の実行であるため、見逃すのはそこからのバックアップだけです。最も適切な結果を得るには、NullUserException の提案と再帰メソッドの外側の時間に従う必要があります。

于 2012-10-10T23:37:02.217 に答える