我有2个不同的程序。首先称为prob1.py,它计算斐波纳契数。第二个叫做prob2.py,用memoisation计算Fibonacci。在名为prob3.py的第三个程序中,我试图为prob1.py打印输出(n,fib(n)的定时)和(n,MemoFib(n)的定时)prob2.py范围(0,40) )。
prob1.py是
import sys
def fib(n):
if n == 0:
return (1)
elif n == 1:
return (1)
else:
return fib(n-1)+fib(n-2)
def main():
result = int(sys.argv[1])
print(fib(result))
main()
和prob2.py是
import sys
array = [0]*101
def MemoFib(n):
if n<=1:
return 1
else:
if(array[n-1]==0):
array[n-1] = MemoFib(n-1)
if(array[n-2]==0):
array[n-2] = MemoFib(n-2)
array[n] = array[n-1] + array[n-2]
return array[n]
def main():
array = [0]*101 # clears the memo between runs
if int(sys.argv[1]) <= 100:
print(MemoFib(int(sys.argv[1])))
else:
print('Enter a value between 0 and 100')
main()
我有以下代码来调用这两个程序来打印出我需要的内容但是我无法将其放入我的代码中。你能解决它吗?如果以下代码不起作用,我也可以使用其他代码。我只需要使用timeit函数打印出(n,Fib(n))和(n,MemoFib(n))。
mytime = timeit.Timer( 'fib(0,40)', 'from prob1 import fib' )
delta = mytime.timeit( 40 )
print "40 runs of fib( 1000000 ) took: " + str( delta ) + " seconds."
print ''
setupStr = 'from prob1 import fib'
setupStr += '; import anotherFile'
mytime = timeit.Timer( 'list_concat( anotherFile.a, anotherFile.b)', setupStr )
print 'calling list_concat from cell.py on a, b, from foo.py:'
delta = mytime.timeit( 5 )
print "1 run of MemoFib( a, b ) took: " + str( delta ) + " seconds."
答案 0 :(得分:0)
当你使用Timer('fib(0,40)', 'from prob1 import fib')
时,你正在设置定时器,用两个参数调用fib
,这会给你一个TypeError告诉你。而是在prob3.py
编辑 - 我现在已对此进行测试并知道它可以执行。
import timeit
repeats = 100
run_code = 'fib(%d)' # formatting mark to enter each time
for n in range(40):
# you can just call the .timeit() function from the module
mytime = timeit.timeit(run_code % n, 'from prob1 import fib', number=repeats)
print ("fib(%d) repeated %d times took %f seconds"%(n,repeats,mytime))
# similar for other one