0

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.

imgoingmad
  • 95
  • 3
  • 10
  • Possible duplicate of [Getting "global name 'foo' is not defined" with Python's timeit](https://stackoverflow.com/questions/551797/getting-global-name-foo-is-not-defined-with-pythons-timeit) – sds Sep 20 '17 at 16:20

1 Answers1

5

Add memo to the list of variables imported from __main__:

mytime2 = timeit.Timer('fibmem({}, memo)'.format(x),'from __main__ import fibmem, memo')
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Yes, this did it. Thank you! – imgoingmad Jan 24 '16 at 17:51
  • 1
    The [`timeit.Timer`](https://docs.python.org/3/library/timeit.html#timeit.timeit) class in Python 3.5 has an optional keyword argument named `globals` which could also be used to solve the problem — although this way works in both Python 2 and 3. – martineau Feb 17 '16 at 02:58