If I have:
['add', 12, 12]
I would just do:
if i[0] == 'add':
a = i[1] i[2]
return a
but what if it's something like
['add', 12, ['add', 12, 12]]
I know that I need to solve the ['add', 12, 12] on the inside first using a recursion but I'm not sure how to do it. And if it's for something like this:
['add', 12, ['mul', 6, ['sub', 6, 4]]]
How would I solve this using recursion?
CodePudding user response:
You can use recursion:
import operator as op
def run_op(l):
if not isinstance(l, list):
return l
return getattr(op, l[0])(*map(run_op, l[1:]))
r = ['add', 12, ['mul', 6, ['sub', 6, 4]]]
print(run_op(r)) #24
CodePudding user response:
Just check if the elements are lists via isinstance
. If so, recursively call your solve function, otherwise just leave it as is.
def solve(i):
if i[0] == "add":
if isinstance(i[1], list):
x = solve(i[1])
else:
x = i[1]
if isinstance(i[2], list):
y = solve(i[2])
else:
y = i[2]
return x y
To implement multiplication, subtraction, etc, just add more cases to the outer if, following similar logic.
CodePudding user response:
Check if the parameter is a list. If it is, assume that the two operands need to go through recursion to get their respective values, then perform the specified operation. If the parameter is not a list simply return it as is.
def calc(A):
if not isinstance(A,list): return A # not a list, return value
op,left,right = map(calc,A) # recurse to get values
if op == "add": return left right # perform operation...
if op == "sub": return left-right
if op == "mul": return left*right
if op == "div": return left/right
print(calc(['add', 12, ['mul', 6, ['sub', 6, 4]]])) # 24