Recursive structure
Lesson 9 of 29 in Coddy's Calculator project using Python course.
The real power of the structure we saw last lesson comes with recursion.
Consider calculation with more than one operator, for example:
- 2 + 3 * 4 + 5
There is an order according to math rules, first we need to calculate 3 * 4 and then all the rest.
The following calculation will be formatted into recursive structure in the possible ways,
['+', ['+', 2, ['*', 3, 4]], 5]['+', 2, ['+', 5, ['*', 3, 4]]]['+', 5, ['+', ['*', 3, 4], 2]]
Notice that the deepest simple structure is always ['*', 3, 4] which is the first to calculate, also note that everything is the basic structure [op, num1, num2].
Some more examples of calculations to recursive structure:
- 2 - 3 ->
['-', 2, 3] - 1 - 2 + 3 ->
['+', ['-', 1, 2], 3] - 1 * 2 - 3 ->
['-', ['*', 1, 2], 3] - 2.3 + 3 / 4.2 - 2 ->
['-', ['+', 2.3, ['/', 3, 4.2]], 2]
Challenge
MediumUpgrade the eval function to support recursive structures as described above.
Notes:
- call
calcfunction when the structure is simple structure, operator with two numbers . - call
evalrecursively if one of the arguments is another structure (list).
Try it yourself
def calc(op, n1, n2=None):
if not isinstance(n1, int) and not isinstance(n1, float):
raise Exception('Invalid number "' + str(n1) + '"')
if n2 is None:
if op == '+' or op == 'add':
return n1
if op == '-' or op == 'sub':
return -n1
raise Exception('Invalid operator "' + op + '"')
if not isinstance(n2, int) and not isinstance(n2, float):
raise Exception('Invalid number "' + str(n2) + '"')
if op == '+' or op == 'add':
return n1 + n2
if op == '-' or op == 'sub':
return n1 - n2
if op == '*' or op == 'mul':
return n1 * n2
if op == '/' or op == 'div':
if n2 == 0:
raise Exception("Division by zero")
return n1 / n2
if op == '%' or op == 'mod':
if n2 == 0:
raise Exception("Division by zero")
return n1 % n2
if op == '^' or op == 'pow':
return n1 ** n2
raise Exception('Invalid operator "' + op + '"')
def eval(lst):
op = lst[0]
n1 = lst[1]
n2 = lst[2]
return calc(op, n1, n2)