#please use comments Postfix notation is an unambiguous way of writing an arithm
ID: 3870534 • Letter: #
Question
#please use comments
Postfix notation is an unambiguous way of writing an arithmetic expression without parenthesis. It is defined so that if “(exp1) op (exp2)” is a normal, fully parenthesized expression whose operation is op, the postfix version of this is “(pexp1) (pexp2) op” where pexp1 and pexp2 are the postfix version of the original expression. For example: ( ( 5 + 2 ) * ( 8 - 3 ) / 4) is 5 2 + 8 3 - * 4 / Develop a non recursive program to evaluate an expression in postfix notation using stacks. ***python
Explanation / Answer
python code to evalvate the given expression :
#!/usr/bin/python
#prasad.manigandla.com
postfix = []
temp = []
operator = -10
operand = -20
leftparentheses = -30
rightparentheses = -40
empty = -50
def precedence(s):
if s is '(':
return 0
elif s is '+' or '-':
return 1
elif s is '*' or '/' or '%':
return 2
else:
return 99
def typeof(s):
if s is '(':
return leftparentheses
elif s is ')':
return rightparentheses
elif s is '+' or s is '-' or s is '*' or s is '%' or s is '/':
return operator
elif s is ' ':
return empty
else :
return operand
infix = raw_input("Enter the infix notation to solve the equation : ")
for i in infix :
type = typeof(i)
if type is leftparentheses :
temp.append(i)
elif type is rightparentheses :
next = temp.pop()
while next is not '(':
postfix.append(next)
next = temp.pop()
elif type is operand:
postfix.append(i)
elif type is operator:
p = precedence(i)
while len(temp) is not 0 and p <= precedence(temp[-1]) :
postfix.append(temp.pop())
temp.append(i)
elif type is empty:
continue
while len(temp) > 0 :
postfix.append(temp.pop())
print "It's postfix solved notation is ",''.join(postfix) ;
here is the sample o/p:Here we are giving the infix notation as to resolve the postfix notation:
( ( 5 + 2 ) * ( 8 - 3 ) / 4)
=>((5+2)*(8-3))4/
=>(5+2)(8-3)*4/
=>52+83-*4/
here is the conversion of infix to postfix onversion using simple ruby code
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.