I am using pyparsing to parse a nested expression which is formed by delimited lists but which includes some basic arithmetic (just multiplication, for instance). A sample expression could look like this:
(A, B, 2 * C, 3 * ( D, E, 2 * F, 3 *(G, H)), I )
The output should unfold the arithmetic:
( A, B, C, C, D, E, F, F, G, H, G, H, G, H, D, E, F, F, G, H, G, H, G, H, D, E, F, F, G, H, G, H, G, H, I )
Could somebody give me hint how to approach the problem?
I started like follows: since there's just the operation multiplication, I decided to use the '*' character as a delimiter in a somewhat weird list:
import pyparsing as pp
oddDelim = pp.Or([',', '*'])
weirdList = pp.Optional(',').suppress() + \
pp.delimitedList(pp.Or([pp.alphas, pp.pyparsing_common.number]), delim = oddDelim, combine = False) + \
pp.Optional('*').suppress()
nestedTest = pp.nestedExpr(content = weirdList)
Using this nestedTest expression I get a reasonable result:
[['A', 'B', 2, 'C', 3, ['D', 'E', 2, 'F', 3, ['G', 'H']], 'I']]
but I don't know how should I parse the tokens in order to properly unfold the arithmetics.
Instead of iterating over the tokens sequentially in a FOR loop, I would ideally like to start unfolding the arithmetic from the highest degree of nesting and progressively going down. But I don't know how...
Is nestedExpr the way to go? Or should I change the approach and use Forward or maybe infixNotation? I am very new into pyparsing I would be very grateful if I got some hints/ideas on this.
Thanks very much in advance for your help!
Cheers, Pau