I have a dictionary of many expressions, for example
g={'asd':x+y,'sss':x-y}
I would like to define two functions aa and bb that return the evaluated value of these expressions.
g={'asd':x+y,'sss':x-y}
def aa(x,y):
return g['asd']
def bb(x,y):
return g['sss']
aa(2,3)
However, I cannot make it correct.
Does anyone know how to do this in python?
Moreover, in fact I have many variables rather only x,y
, but variables like x1,x2,x3...x100.
I also have many functions.
If to do it this way:
g = { 'asd': lambda x, y: math.exp(x)**y, 'sss': lambda x, y: x - y }
def aa(x,y):
return g['asd'](x,y)
def bb(x,y):
return g['sss'](x,y)
bb(2,3)
I will have to copy x1,x2,x3...x100 for 100 times. This is too huge.
You can use eval:
g={'asd':'x+y','sss':'x-y'}
def aa(x,y):
return eval(g['asd'])
def bb(x,y):
return g['sss']
aa(2,3)