101. A calculator with brackets
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, so10 - 2 - 3is 5 and100 / 10 / 5is 2.- Division keeps the whole part, rounding toward zero:
7 / 2is 3 and-7 / 2is -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)or3 * -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
expression = "1 + 2 * 3"7Example 2
expression = "(1 + 2) * 3"9Example 3
expression = "-7 / 2"-3Constraints
expressionhas 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.
- First split the text into tokens, the numbers and the symbols, skipping spaces:
re.findall(r"\d+|[-+*/()]", expression)does it in one line. - Write three functions that each take the tokens and a position, and return a value and the position after it:
parse_sum(terms joined by+and-),parse_product(factors joined by*and/) andparse_factor(a number,-and a factor, or(sum)). parse_factorcallsparse_sumfor a bracket: that is the recursion. Divide toward zero with whole numbers:abs(a) // abs(b), with the minus sign put back when exactly one of them is negative.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.