Abhishek,
I hesitate to propose this idea, because there's got to be a better (more
conventional) way of doing this. Anyway consider
this:
>>> x = "a+b"; y = "x*a; z = "x+y" # Your definitions
>>> import SE
>>> def f (x, y, z):
substitutions = 'z=(%s) | y=(%s) | x=(%s)' % (z, y, x)
print 'substitutions:', substitutions
Formula_Expander = SE.SE (substitutions)
formula = 'x + y + z'
expanded_formula = Formula_Expander (formula)
print 'expanded_formula:', expanded_formula
a = 3; b = 4
print 'eval (expanded_formula):', eval (expanded_formula)
w = eval (Formula_Expander ('y * b'))
print 'w', w
>>> f (x, y, z)
substitutions: z=(x+y) | y=(x*a) | x=(a+b)
expanded_formula: (a+b) + ((a+b)*a) + ((a+b)+((a+b)*a))
eval (expanded_formula): 56
w 84
Well--- it's kind of neat the way it expands the formula. But why not just
write functions? As you say, the expansion has to be done
in exactly the right order to complete.
If you want to run this example you'll find SE here:
http://cheeseshop.python.org/pypi/SE/2.2%20beta
Regards
Frederic
----- Original Message -----
From: <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: <[email protected]>
Sent: Thursday, August 31, 2006 1:15 PM
Subject: Using eval with substitutions
> >>> a,b=3,4
> >>> x="a+b"
> >>> eval(x)
> 7
> >>> y="x+a"
>
> Now I want to evaluate y by substituting for the evaluated value of x.
> eval(y) will try to add "a+b" to 3 and return an error. I could do
> this,
> >>> eval(y.replace("x",str(eval(x))))
> 10
>
> but this becomes unwieldy if I have
> >>> w="y*b"
> and so on, because the replacements have to be done in exactly the
> right order. Is there a better way?
>
> Thanks,
> Abhishek
>
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list