# the stack class works like a stack
class stack:
def __init__(self):
self.stack = []
def add(self, item):
self.stack.append(item)
def remove(self):
end = self.stack[-1]
self.stack.pop(-1)
return end
# allows iteration backwards through the stack | Magic method
def __iter__(self):
for op in self.stack:
yield self.stack[-1]
def __len__(self):
return len(self.stack)
def print(self):
pro = ", ".join(self.stack)
print(f"Stack: {pro}")
# the actual code
class converter:
def __init__(self, infix):
self.operator_stack = stack()
#self.b_depth = 0
self.infix = infix
self.operators = ["+", "-", "*", "/", "^","×", "÷", "−"]
self.postfix = ""
# the func
def convert(self):
for char in self.infix:
if char == "(":
pass
#self.b_depth += 1
# how it works is when theres a ) it empties the stack onto the
# postfix expression if theres items in the stack
elif char == ")":
#self.b_depth -= 1
if len(self.operator_stack) > 0:
for i in range(len(self.operator_stack)):
self.postfix = self.postfix + " " +
self.operator_stack.remove()
# adds operator to the stack
elif char in self.operators:
self.operator_stack.add(char)
self.postfix = self.postfix + " "
elif char == " ":
pass
# if its an operand add to the postfix
else:
self.postfix = self.postfix + char
return self.postfix
# place where its executed
if __name__ == "__main__":
# example input
# print(converter("((15 ÷ (7 − (1 + 1))) × 3) − (2 + (1 + 1))").convert())
print(converter(input("Enter Infix expression: ")).convert())
# Working one hundred billion percent correctly !!