I have to make a function where the input is a tuple consisting of 3 elements: elements 1 and 3 are numbers or other tuples with the same structure, and the second element is a string indicating an operation. An example would be (10, '-', (5, '*', 3)) and should return -5. The problem is that the function must be recursive and I can't find a way of working with tuples with recursive functions.
def evaluate(equation):
if type(equation[0]) != tuple and type(equation[2]) != tuple:
if equation[1] == " ":
return equation[0] equation[2]
if equation[1] == "*":
return equation[0] * equation[2]
if equation[1] == "-":
return equation[0] - equation[2]
if equation[1] == "/":
return equation[0] / equation[2]
I managed to create a foundation to operate, but I can't find an algorithm that finds all the empty tuples and keeps those values to operate latter.
CodePudding user response:
Evaluate the left and right sides of the tuple before performing the operation.
def evaluate(equation):
left, operation, right = equation
if type(left) == tuple:
left = evaluate(left)
if type(right) == tuple:
right = evaluate(right)
if operation == " ":
return left right
elif operation == "*":
return left * right
elif operation == "-":
return left - right
elif operation == "/":
return left / right