0% found this document useful (0 votes)
6 views2 pages

Practical No - 9

Good

Uploaded by

Aavez Asif Mukri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Practical No - 9

Good

Uploaded by

Aavez Asif Mukri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

NAME:KAUSHIK RODPALKAR

STD:SYCS B
ROLL NO:5378

Practical no 9

Implement Program for -


a Infix to Postfix conversion
Code:
operators = set(['+', '-', '*', '/', '(', ')', '^'])
priority = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
def infix_to_postfix(expression):
stack = []
output = ''
for ch in expression:
if ch not in operators:
output += ch
elif ch == '(':
stack.append('(')
elif ch == ')':
while stack and stack[-1] != '(':
output += stack.pop()
stack.pop()
else:
while stack and stack[-1] != '(' and priority[ch] <= priority[stack[-1]]:
output += stack.pop()
stack.append(ch)
while stack:
output += stack.pop()
return output
expression = input('Enter infix Expression: ')
print('Infix expression:', expression)
print('Postfix expression:', infix_to_postfix(expression))

OUTPUT:
NAME:KAUSHIK RODPALKAR
STD:SYCS B
ROLL NO:5378

b) Postfix Evaluation:
Code:
def postfix_evaluation(s):
s = s.split()
n = len(s)
stack = []
for i in range(n):
if s[i].isdigit():
stack.append(int(s[i]))
elif s[i] == "+":
a = stack.pop()
b = stack.pop()
stack.append(int(a) + int(b))
elif s[i] == "*":
a = stack.pop()
b = stack.pop()
stack.append(int(a) * int(b))
elif s[i] == "/":
a = stack.pop()
b = stack.pop()
stack.append(int(b) / int(a))
elif s[i] == "-":
a = stack.pop()
b = stack.pop()
stack.append(int(b) - int(a))

return stack.pop()

s = "10 2 8 * + 3 -"
val = postfix_evaluation(s)
print("Post-fix Evaluation Value:", val)
OUTPUT:

You might also like