Ask Your Question
0

Using timeit in an interact without string formatting

asked 2013-03-05 21:21:49 +0100

kcrisman gravatar image

I wanted the following to work, but it didn't. Anyone have an idea how to make it do so?

def T(n):
    top = ceil(math.sqrt(n))
    print top

@interact
def _(n=6739815371):
    T(n)
    timeit('T(n)')

Instead I had to do

def T(n):
    top = ceil(math.sqrt(n))
    print top

@interact
def _(n=6739815371):
    T(n)
    timeit('T(%s)'%n)

But I feel like the first thing did indeed work in the past (though I tried it with a Sage from 2010 to no avail).

I guess in some sense this is a silly question - 'T(n)' is a string, pure and simple. At the same time, in the command line

sage: def T(n):
....:         top = ceil(math.sqrt(n))
....:         print top
....:     
sage: n=6739815371
sage: timeit('T(n)')
625 loops, best of 3: 5.96 µs per loop

and 'T(n)' is a string there too. So what is different about interact that this doesn't work (in Sage or the cell server)?

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted
2

answered 2013-03-12 09:03:35 +0100

ndomes gravatar image

As far as n is in the global namespace, the error message of your example is misleading. My example below gives the error message:

NameError: global name 'k' is not defined

def T(k):
    top = ceil(math.sqrt(k))
    print top   

@interact
def _(k=6739815371):
    timeit('T(k)')

So timeit apparently looks in the global namespace.

My first try was:

@interact
def _(k=6739815371):
    global k
    timeit('T(k)')

Traceback (most recent call last): def _(k=6739815371): File "", line 1, in <module> File "/tmp/tmpVWF0nv/___code___.py", line 8 @interact SyntaxError: name 'k' is local and global

So we have to outwit the @interact function:

@interact
def _(k0=6739815371):
    global k
    k = k0
    timeit('T(k)')
edit flag offensive delete link more
1

answered 2013-03-06 02:11:24 +0100

ppurka gravatar image

I suspect it is some python idiosyncrasy. It is somehow not getting the variable n as defined in the function declaration. The following works (for some reason using n=n again didn't work, probably because n is defined globally to be some function):

def T(n):
    top = ceil(math.sqrt(n))
    print top

@interact
def _(k=6739815371):
    T(k)
    k = k
    timeit('T(k)')
edit flag offensive delete link more

Comments

Huh, bizarre.

kcrisman gravatar imagekcrisman ( 2013-03-06 13:38:00 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-03-05 21:21:49 +0100

Seen: 616 times

Last updated: Mar 12 '13