Re: Using eval with substitutions



abhishek@xxxxxxxxxxxxxxxx wrote:

So as you say, I could do:
x=eval(x), y=eval(y), z=eval(z) and finally eval("z+y+x") but the
problem is that the initial strings are in no particular order, so I
don't know the sequence in which to perform the first 3 evaluations. I
was wondering if there was a simple way to 'pattern-match' so that the
required substitutions like z->x+y->x+x*a->(a+b)+(a+b)*a could be done
automatically.

Sounds a bit of an odd thing to do, but:

def evaluate(var, names):
expr = names[var]
names['__builtins__'] = {}
if isinstance(expr, basestring):
del names[var]
code = compile(expr, "<%s>"%var, "eval")
for v in code.co_names:
evaluate(v, names)
names[var] = eval(code, names, names)
del names['__builtins__']
return names[var]

names = { 'a': 3, 'b': 2, 'x': 'a+b', 'y': 'x*a', 'z': 'x+y' }
evaluate('z', names)
20
names
{'a': 3, 'b': 2, 'y': 15, 'x': 5, 'z': 20}


.



Relevant Pages

  • Re: .99999... still=/= 1
    ... > placeholders in the infinite long area *N were already occupied. ... decimal digit strings. ... sequence, and it is understood that any other sequence that happens to ... To describe a member of *N, for example, I can ...
    (sci.math)
  • Re: Pitman CSI Formula - for all values of X
    ... The total number of strings with HD of 1 relative to the chosen ... specific sequence space, which contains it as well as all of the other ... within a particular Hamming Distance of the reference string. ... But patterns don't necessarily imply deliberate design, ...
    (talk.origins)
  • Re: Pitman CSI Formula - for all values of X
    ... The total number of strings with HD of 1 relative to the chosen ... specific sequence space, which contains it as well as all of the other ... within a particular Hamming Distance of the reference string. ... radio signals, but made up 0s and 1s. ...
    (talk.origins)
  • Re: Pitman CSI Formula - for all values of X
    ... The total number of strings with HD of 1 relative to the chosen ... specific sequence space, which contains it as well as all of the other ... within a particular Hamming Distance of the reference string. ... several subsequent posts that your examples were "radio signals", ...
    (talk.origins)
  • Re: Pitman CSI Formula - for all values of X
    ... The total number of strings with HD of 1 relative to the chosen ... specific sequence space, which contains it as well as all of the other ... within a particular Hamming Distance of the reference string. ... radio signals, but made up 0s and 1s. ...
    (talk.origins)