150 XP

101. A calculator with brackets

Expert parsing recursion

Write a function calculate(expression) that takes an arithmetic expression as a string and returns its value as a whole number, without eval():

  • Numbers are whole numbers of one or more digits. The operators are +, -, * and /, and brackets ( ) can group any part.
  • * and / are done before + and -; otherwise the operators work from left to right, so 10 - 2 - 3 is 5 and 100 / 10 / 5 is 2.
  • Division keeps the whole part, rounding toward zero: 7 / 2 is 3 and -7 / 2 is -3.
  • A minus sign can also make a number or a bracket negative: at the start, after (, or after another operator, as in -(2 + 3) or 3 * -2.
  • Spaces can appear anywhere between numbers and symbols, and mean nothing.

One way in is to write one function for each level of precedence, each calling the next: sums are made of products, products of factors, and a factor is a number, a minus sign and a factor, or a whole expression in brackets.

Example 1

Inputexpression = "1 + 2 * 3"
Output7
Explanation2 * 3 first, then 1 + 6.

Example 2

Inputexpression = "(1 + 2) * 3"
Output9
ExplanationThe brackets come first: 3 * 3.

Example 3

Inputexpression = "-7 / 2"
Output-3
Explanation-3.5, rounded toward zero.

Constraints

  • expression has 1 to 200 characters and is always a valid expression as described.
  • No division is by zero, and every value along the way is from -10^12 to 10^12.

Submit also runs 15 more tests you can't see.

Code
def calculate(expression):
    """Work out an arithmetic expression.

    expression: str, whole numbers, + - * /, brackets and
        spaces
    Returns: int, its value, division rounding toward 0
    """
    # Write your code here
    pass