jack - 8 months ago 50

Python Question

If i have nested list as below, how do i first access

`['*', '5', '8']`

`['*',[result_from_previous_step],'9']`

`['*', ['*', ['*', '5', '8'], '9'], '10']`

This seems some what like evaluating a tree to me but in bottom up fashion

Answer Source

The most straightforward solution is to write a recursive function that calls itself to evaluate the inner expressions.

```
def evaluate(expression):
operation, operand1, operand2 = expression
if isinstance(operand1, (list, tuple)):
operand1 = evaluate(operand1)
if isinstance(operand1, (list, tuple)):
operand2 = evaluate(operand2)
operand1, operand2 = int(operand1), int(operand2)
if operation == "*":
return operand1 * operand2
elif operation == "+":
return operand1 + operand2
elif operation == "/":
# keep the result an int if possible
result1 = operand1 // operand2
result2 = float(operand1) / operand2
return result1 if result1 == result2 else result2
elif operation == "-":
return operand1 - operand2
evaluate(['*', ['*', ['*', '5', '8'], '9'], '10']) # 3600
```