[Tutor] Advise...
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Wed Jan 26 20:07:43 CET 2005
> > There has been alot of talk on this list about using list comprehensions
> > lately, and this could be one of those useful places. While I don't
> > have time to experiment with real code, I would suggest changing your
> > function to look like:
> >
> > steps = [ min_x + i*delta_x for i in range(steps) ]
> > totalarea = sum([ eval(func_x)*delta_x for x in steps ])
>
> Calling eval() there in the inner loop might be costly, because Python
> needs to do extra work to tokenize and parse the string, every time
> through the iteration. We want to reduce the work done in tight inner
> loops like that.
>
> We can do some of that work up front by compiling the code. Here's some
> hacky code to do the compilation up front:
>
> ###
> >>> def makeFunction(expressionString):
> ... compiledExp = compile(expressionString, 'makeFunction', 'eval')
> ... def f(x):
> ... return eval(compiledExp, {}, {'x' : x})
> ... return f
> ...
> ###
Oh! There's a slightly simpler way to write that makeFunction():
###
>>> def makeFunction(s):
... return eval("lambda x: " + s)
...
###
It even has a little less overhead than the previous code.
###
>>> timeIt(myFunctionOriginal)
0.035856008529663086
>>>
>>> timeIt(makeFunction("3*x*x"))
0.00087714195251464844
###
Best of wishes!
More information about the Tutor
mailing list