Thanks everyone!
Kent started the suggestion of making a code object, but everyone else seems to have worked their way to it.
Beautiful! I only have to call exec once, and it cuts down time considerably.
Here is the new code. Jacob Schmidt
Please remind me if I've forgotten anything.
### Start ################### from __future__ import division from math import * import psyco psyco.full()
def reimannsum(fofx,x,max1): total = 0 step = 1e-5 exec "def f(x): return %s" % fofx while x <= max1: total = total+f(x) x = x+step return abs(total*step)
fofx = raw_input("What is the function? ") minimum = raw_input("What is the minimum? ") maximum = raw_input("What is the maximum? ") minimum = float(minimum) maximum = float(maximum) print reimannsum(fofx,minimum,maximum) #### End ##############################
If the user must be able to enter in the function, then it would bebetterto evaluate this once and turn it into some sort of function thatyou cancall inside the loop (it's the eval that is so expensive). How todo thatdepends a lot on how complex the possible functions can be (ifthey'll onlyinclude 'x*+/-' and numbers, for example, it's not so tricky).
exp = raw_input('Type expression') func = eval('lambda x: " + exp)
print func(42)
etc...
Or if you really can't grokm lambda:
exec('def func(x): return " + exp)
should do the same...
Alan G.
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor