Reputation: 95
I've got a simple Fibonacci function that uses memoisation and it works just fine on its own. However when I want to time it using timeit, I get "NameError: global name 'memo' is not defined", even though it is.
#!/usr/bin/python
import sys
import timeit
memo = [0] * 100
def fibmem(n,memo):
#function things
for x in range(1,40):
mytime2 = timeit.Timer('fibmem('+str(x)+', memo)','from __main__ import fibmem')
delta2 = mytime2.timeit(1)
print str(x) + ' ' +str(delta2)
memo[:] = []
I've tried looking up what it might be, but most of the answers involve including the from __main__ import
and that isn't the problem here. I'm sure it's still something to do with scoping, but I am very new to timeit, so I have no idea.
Upvotes: 0
Views: 1356
Reputation: 880757
Add memo
to the list of variables imported from __main__
:
mytime2 = timeit.Timer('fibmem({}, memo)'.format(x),'from __main__ import fibmem, memo')
Upvotes: 5