Python implement a class that uses a stack to convert an infix expression to a postfix expression.

Python implement a class that uses a stack to convert an infix expression to a postfix expression.



class InfixToPostfix:
def __init__(self):
# Stack to hold operators
self.stack = []
# Precedence dictionary for operators
self.precedence = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3
}

def is_operator(self, char):
"""Check if a character is an operator."""
return char in self.precedence

def is_operand(self, char):
"""Check if a character is an operand (alphabet or digit)."""
# Allowing letters (a-z, A-Z) and digits (0-9)
return char.isalnum()

def is_left_parenthesis(self, char):
return char == '('

def is_right_parenthesis(self, char):
return char == ')'

def get_precedence(self, operator):
"""Get the precedence value of an operator."""
return self.precedence.get(operator, 0)

def convert(self, expression):
"""Convert an infix expression to postfix notation."""
# Remove spaces from the expression
expression = expression.replace(" ", "")
postfix_result = []

for char in expression:
# If character is an operand, add it to output
if self.is_operand(char):
postfix_result.append(char)

# If character is '(', push it to stack
elif self.is_left_parenthesis(char):
self.stack.append(char)

# If character is ')', pop and output from stack until '(' is found
elif self.is_right_parenthesis(char):
while self.stack and not self.is_left_parenthesis(self.stack[-1]):
postfix_result.append(self.stack.pop())
# Pop the '(' from the stack
if self.stack:
self.stack.pop()

# If character is an operator
elif self.is_operator(char):
# While stack top is an operator with higher or equal precedence,
# pop it to output
while (self.stack and self.is_operator(self.stack[-1]) and
self.get_precedence(self.stack[-1]) >= self.get_precedence(char)):
postfix_result.append(self.stack.pop())
# Push current operator to stack
self.stack.append(char)

# Pop all remaining operators from the stack
while self.stack:
postfix_result.append(self.stack.pop())

# Join the list to form the final postfix expression
return ''.join(postfix_result)

# --- Example Usage ---
infix_to_postfix = InfixToPostfix()

# Test cases
expr1 = "A + B * C"
print(f"Infix: {expr1}")
postfix1 = infix_to_postfix.convert(expr1)
print(f"Postfix: {postfix1}")

expr2 = "(A + B) * C"
print(f"\nInfix: {expr2}")
postfix2 = infix_to_postfix.convert(expr2)
print(f"Postfix: {postfix2}")

expr3 = "A * B + C / D"
print(f"\nInfix: {expr3}")
postfix3 = infix_to_postfix.convert(expr3)
print(f"Postfix: {postfix3}")

expr4 = "A + B * C ^ D"
print(f"\nInfix: {expr4}")
postfix4 = infix_to_postfix.convert(expr4)
print(f"Postfix: {postfix4}")