[PYTHON] - POSTFIX EXPRESSIONS The stack function I have already completed and i
ID: 3714507 • Letter: #
Question
[PYTHON] - POSTFIX EXPRESSIONS
The stack function I have already completed and inserted into the code. It works from previous lab so assuming it should work here as well.
I need help with the postfix expression. thank you for your time <3
Using your Stack implementation from Lab#10, write the function posfir(expression), where expression is the string of a postfix expression. The function returns the value after evaluating such expression. Function notes Expression Operators: + -,/, *,A (a b is a to the power b) The postfix expression is a string of operands and operators delimited by spaces - EXAMPLE >>> postfix ( "4 7 6 * + 10 -'*) # Infix: 4+7*6-10 36 >>> postfix ("2 4 ^ 3 + 2 5 / -") # Infix: (2-4) +3-2/5 18.6 >>> postfix ("16 42 3 _ - 7 + 5 *") # Infix: (16-(42-3)+7)*5 -80 >>> postfix ("10 5 / 2 +") # Infix: (10/51+2 # Depending on your implementation, 4.0 is also a correct answer Tips Go to http://www.mathblog.dk/tools/infix-postfix-converter/ to create your test casesExplanation / Answer
def postfix_evaluation(s):
s=s.split()
n=len(s)
stack =[]#change here as per your stack declarations...
for i in range(n):
if s[i].isdigit():
stack.append(float(s[i]))#change append to push... for ur stack class
elif s[i]=="+":
a=stack.pop()
b=stack.pop()
stack.append(float(a)+float(b))
elif s[i]=="*":
a=stack.pop()
b=stack.pop()
stack.append(float(a)*float(b))
elif s[i]=="/":
a=stack.pop()
b=stack.pop()
stack.append(float(b)/float(a))
elif s[i]=="-":
a=stack.pop()
b=stack.pop()
stack.append(float(b)-float(a))
elif s[i]=="^":
a=stack.pop()
b=stack.pop()
stack.append(float(b)**float(a))
return stack.pop()
s="4 7 6 * + 10 -"
val=postfix_evaluation(s)
print(val)
s1="2 4 ^ 3 + 2 5 / -"
val1=postfix_evaluation(s1)
print(val1)
output:
>>>
36.0
18.6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.