31Evaluate an Expression

    Hardparsingrecursion

    Write calculate(expr) that evaluates an arithmetic expression made of whole numbers, +, -, *, brackets and spaces, and returns the integer result.

    Multiplication happens before addition and subtraction, and operators of the same kind go left to right, just like in Python.

    Examples

    Example 1
    >>> calculate('2 + 3 * 4')
    14
    Example 2
    >>> calculate('(2 + 3) * 4')
    20

    Good to know

    • Don't use eval(). The point is to write the parser yourself.
    • There is no division and no negative numbers written as -5.

    Run examples checks the 2 examples above. Submit runs all 8 tests, including hidden edge cases, and marks the challenge solved.

    solution.py
    Loading Python…

    Test results show up here

    Write calculate in the editor, then run the examples. Use print() freely: its output is shown for each test.