I'm trying to build a python function from a input given in Reverse Polish notation. My function is supposed to be able to take in x
and y
values as parameters and return the value of the function for the respective x
and y
.
My input is for example:
"x 1 + y 3 * +"
My expected result would be a function object similar to:
fun = lambda x,y: x+1+y*3
So that I can call fun(1,2)
and get 9
as the result.
So far I can evaluate input without variables and give the result.
bin_ops = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b),
}
def eval(expression):
tokens = expression.split()
stack = []
for token in tokens:
if token in bin_ops:
arg2 = stack.pop()
arg1 = stack.pop()
result = bin_ops[token](arg1, arg2)
stack.append(result)
else:
stack.append(float(token))
return stack.pop()
txt = '2 1 + 2 3 * +'
print(eval(txt)) # prints 9.0
Can you help me how to build a function instead of directly the result
and how I can process variables (such as x
and y
) properly?