jack jack - 9 days ago 4
Python Question

Python : Accessing elements of inner most list in nested lists

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

['*', '5', '8']
(innermost list) so that i can perform multiplication and then move on to next innermost list i.e
['*',[result_from_previous_step],'9']
and so on till outer most list is found

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


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

Answer

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
Comments