quiz about symbolic manipulation
Michael Hudson
mwh at python.net
Mon Dec 16 09:24:59 EST 2002
bokr at oz.net (Bengt Richter) writes:
> Well, for a toy problem, parsing according to python grammar is probably
> overkill. I.e.,
>
> 'square(square(x+y)+z)+square(x+w)'
>
> becomes
>
> ['eval_input',
> ['testlist',
> ['test',
> ['and_test',
> ['not_test',
> ['comparison',
> ['expr',
> ['xor_expr',
[... and on and on and on ...]
Bengt probably knows this, but you can use the compiler package to
make this very much pleasanter...
>>> compiler.transformer.parse('square(square(x+y)+z)+square(x+w)')
Module(None, Stmt([Discard(Add((CallFunc(Name('square'),
[Add((CallFunc(Name('square'), [Add((Name('x'), Name('y')))], None,
None), Name('z')))], None, None), CallFunc(Name('square'),
[Add((Name('x'), Name('w')))], None, None))))]))
>>> _.node.nodes[0].expr
Add((CallFunc(Name('square'), [Add((CallFunc(Name('square'),
[Add((Name('x'), Name('y')))], None, None), Name('z')))], None, None),
CallFunc(Name('square'), [Add((Name('x'), Name('w')))], None, None)))
Hmm, well the fact that pprint.pprint doesn't know how to deal with
these thigns doesn't help, but these really are nicer to work with :)
Cheers,
M.
--
Famous remarks are very seldom quoted correctly.
-- Simeon Strunsky
More information about the Python-list
mailing list