unfolding recursive expressions

171 Views Asked by At

I've been recently working with recursive expressions in Python. An example of such expression is given as:

['+', [['*', ['i0','i1']], ['*', ['i2','i3']]]]

I'm attempting to transform expressions like these into something I can directly compute, e.g.,

(i0*i1) + (i2*i3)

Intuitively, it seems some form of recursion is needed, however, I cannot wrap my head around this problem for some reason.

Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

A way that can also handle more than two operands:

def transform(e):
    if isinstance(e, str):
        return e
    return '(' + e[0].join(map(transform, e[1])) + ')'

Demo:

>>> transform(['+', [['*', ['i0', 'i1']], ['*', ['i2', 'i3', 'i4']]]])
'((i0*i1)+(i2*i3*i4))'
0
On

Here is a possible solution:

def build_expression(x):
    operator = x[0]
    operand1 = x[1][0] if isinstance(x[1][0], str) else '('+build_expression(x[1][0])+')'
    operand2 = x[1][1] if isinstance(x[1][1], str) else '('+build_expression(x[1][1])+')'
    return operand1 + operator + operand2

You can use it like this:

build_expression(['+', [['*', ['i0','i1']], ['*', ['i2','i3']]]])