Professional Documents
Culture Documents
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
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)
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.