You are on page 1of 4

Reg No: URK22CS1046

Ex. No: 2 Application of Stack - Expression Evaluation and


01-08-23
Conversion
Aim :
To convert the infix expressions to postfix expressions and to evaluate the postfix expressions
with the help of stack data structure.

Description:
Infix Expressions are harder for Computers to evaluate because of the additional work needed
to decide precedence. Infix notation is how expressions are written and recognized by
humans and, generally, input to programs. Given that they are harder to evaluate, they are
generally converted to one of the two remaining forms, the prefix and postfix expressions. A
postfix expression itself determines the precedence of operators (as the placement of
operators in a postfix expression depends upon its precedence). Therefore, for the machine, it
is easier to carry out a postfix expression than an infix expression.
Infix: A+ (B*C-(D/E^F)*G)*H

Postfix: ABC*DEF^/G*-H*+ Algorithm:

Infix to Postfix Conversion


1. Initialize an empty stack to hold operators temporarily.
2. Initialize an empty list to store the output (postfix expression).
3. Read the infix expression from left to right, one character at a time.
4. If the character is an operand (a number or variable), append it to the output list.
5. If the character is an open parenthesis '(', push it onto the stack.
6. If the character is a closing parenthesis ')', pop operators from the stack and append
them to the output list until an open parenthesis '(' is encountered on the top of the
stack. Pop and discard the open parenthesis from the stack.
7. If the character is an operator ('+', '-', '*', '/', '%', '**'), do the following: a. While the
stack is not empty and the precedence of the operator at the top of the stack is greater
than or equal to the precedence of the current operator, pop the operator from the
stack and append it to the output list. b. Push the current operator onto the stack.
8. Continue steps 4 to 7 until all characters in the infix expression are processed.
9. After processing all characters, if there are any operators remaining in the stack, pop
them and append them to the output list.
10. The output list now contains the postfix expression.

Program:
def is_operator(char):
return char in "+-*/%**^"
def precedence(char): if
char == '+' or char == '-':
return 1 elif char == '*' or char == '/'
or char == '%':
return 2 elif char == '**'
or char == '^':
return 3 return 0 def
infix_to_postfix(expression):
output = [] operator_stack = []
for char in expression: if
char.isdigit() or char.isalpha():
output.append(char)
elif char == '(':
operator_stack.append(char)
elif char == ')':
while operator_stack and operator_stack[-1] != '(':
output.append(operator_stack.pop())
operator_stack.pop() # Remove the corresponding '(' elif
is_operator(char):
while operator_stack and precedence(operator_stack[-1]) >= precedence(char):
output.append(operator_stack.pop())
operator_stack.append(char) while
operator_stack:
output.append(operator_stack.pop()) return
''.join(output)

expression = input("Enter the infix expression: ")


postfix_expression = infix_to_postfix(expression) print("Postfix
expression:", postfix_expression)
Output:

Algorithm: Postfix Expression Evaluation


1. Initialize an empty stack to store operands.
2. Scan the given postfix expression from left to right, one character at a time.
3. If the current character is a digit, it is an operand. Convert it to an integer and push it
onto the stack.
4. If the current character is an operator ('+', '-', '*', '/', '%', '**'), do the following: a. Pop
the top two elements from the stack. Let's call them operand2 and operand1. b.
Evaluate the operation "operand1 operator operand2" based on the current operator. c.
Push the result of the evaluation back onto the stack.
5. Continue steps 3 and 4 until all characters in the postfix expression are processed.
6. After processing all characters, the final result will be the only element left in the
stack.
7. If there is more than one element in the stack or no elements at all, the postfix
expression is invalid.

Program:
def is_operator(char):
return char in "+-*/%**" def
evaluate_postfix(expression):
stack = [] for char
in expression:
if char.isdigit():
stack.append(int(char))
elif is_operator(char):
operand2 = stack.pop()
operand1 = stack.pop() if char
== '+':
result = operand1 + operand2
elif char == '-':
result = operand1 - operand2
elif char == '*':
result = operand1 * operand2
elif char == '/':
result = operand1 / operand2
elif char == '%':
result = operand1 % operand2
elif char == '**':
result = operand1 ** operand2
stack.append(result) return stack[0] if
stack else None
postfix_expression = input("Enter the postfix expression: ")
result = evaluate_postfix(postfix_expression) if result is not
None:
print("Result:", result) else:
print("Invalid postfix expression.")

Output:

Result:
These program successfully demonstrate the implementation of infix to postfix conversion
and postfix expression evaluation.

You might also like