8. Evaluation of Prefix expression
Evaluation of Prefix expression¶
In [1]:
Copied!
prefix_expression = '- + 2 * 3 4 / 16 ^ 2 3'
prefix_expression_list = prefix_expression.split()
prefix_expression = '- + 2 * 3 4 / 16 ^ 2 3'
prefix_expression_list = prefix_expression.split()
In [2]:
Copied!
def prefix_expression_evaluation(expression):
operators = ["+", "-", "/", "*", "^"]
rev_prefix_expression = expression[::-1]
print(rev_prefix_expression)
stack = []
for i in rev_prefix_expression:
if i in operators:
a = stack.pop()
b = stack.pop()
if i == "^":
i = "**"
s = a+i+b
print(s)
ans = str(eval(a+i+b))
print("pushing {} onto stack".format(ans))
stack.append(ans)
else:
print("pushing {} onto stack".format(i))
stack.append(i)
return float(stack[-1])
def prefix_expression_evaluation(expression):
operators = ["+", "-", "/", "*", "^"]
rev_prefix_expression = expression[::-1]
print(rev_prefix_expression)
stack = []
for i in rev_prefix_expression:
if i in operators:
a = stack.pop()
b = stack.pop()
if i == "^":
i = "**"
s = a+i+b
print(s)
ans = str(eval(a+i+b))
print("pushing {} onto stack".format(ans))
stack.append(ans)
else:
print("pushing {} onto stack".format(i))
stack.append(i)
return float(stack[-1])
In [3]:
Copied!
prefix_expression_evaluation(prefix_expression_list)
prefix_expression_evaluation(prefix_expression_list)
['3', '2', '^', '16', '/', '4', '3', '*', '2', '+', '-'] pushing 3 onto stack pushing 2 onto stack 2**3 pushing 8 onto stack pushing 16 onto stack 16/8 pushing 2.0 onto stack pushing 4 onto stack pushing 3 onto stack 3*4 pushing 12 onto stack pushing 2 onto stack 2+12 pushing 14 onto stack 14-2.0 pushing 12.0 onto stack
Out[3]:
12.0