Data Structures
In this exercise, we’re going to write a simple “infix” calculator.
Infix is the normal way we represent arithmetic expressions, like:
1 + 2
1 + ( 2 * 3 )
We’re going to have a simple, restricted version of our normal math, though.
Rather than having to deal with order-of-operators of different operators (multiply-before-add, for example), we’re only going to allow simple expressions, with a left-hands-side, one operator, and right-hand-side.
We can use parenthesized-expressions for our left-hand side and our right-hand side, though, so these are legal:
2 * ( 1 + 2 )
( 2 * 1 ) + 2
( ( 1 + 2 ) * ( 3 + 4 ) ) - ( 2 * ( 1 + 3 ) )
We want a function that take an expression like those, as a string, and returns the results.
You can assume the expressions are valid syntax:
The numbers are always integers
The only operators are +, -, *, and /
The left-hand side can only either be a simple number or a parenthesized expression
The right-hand side can only either be a simple number or a parenthesized expression
There will always be spaces around every part of the expression, so it will be “1 + ( 2 * 3 )” (so you don’t have to worry about separating numbers from operators or parentheses, as you would have to with “1 + (2*3)”.
We’ve given you a file, infix.py, with a stub function:
def calc(s):
"""Simple infix calculator."""