-1

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!

sdgaw erzswer
  • 2,182
  • 2
  • 26
  • 45

2 Answers2

2

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))'
superb rain
  • 5,300
  • 2
  • 11
  • 25
1

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']]]])
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50