"""
Output:
Enter an Infix Equation = a + b ^c
Symbol | Stack | Postfix
----------------------------
c | | c
^ | ^ | c
b | ^ | cb
+ | + | cb^
a | + | cb^a
| | cb^a+
a+b^c (Infix) -> +a^bc (Prefix)
"""
def infix_2_postfix(infix):
stack = []
post_fix = []
priority = {
"^": 3,
"*": 2,
"/": 2,
"%": 2,
"+": 1,
"-": 1,
}
print_width = len(infix) if (len(infix) > 7) else 7
print(
"Symbol".center(8),
"Stack".center(print_width),
"Postfix".center(print_width),
sep=" | ",
)
print("-" * (print_width * 3 + 7))
for x in infix:
if x.isalpha() or x.isdigit():
post_fix.append(x)
elif x == "(":
stack.append(x)
elif x == ")":
while stack[-1] != "(":
post_fix.append(stack.pop())
stack.pop()
else:
if len(stack) == 0:
stack.append(x)
else:
while len(stack) > 0 and priority[x] <= priority[stack[-1]]:
post_fix.append(stack.pop())
stack.append(x)
print(
x.center(8),
("".join(stack)).ljust(print_width),
("".join(post_fix)).ljust(print_width),
sep=" | ",
)
while len(stack) > 0:
post_fix.append(stack.pop())
print(
" ".center(8),
("".join(stack)).ljust(print_width),
("".join(post_fix)).ljust(print_width),
sep=" | ",
)
return "".join(post_fix)
def infix_2_prefix(infix):
infix = list(infix[::-1])
for i in range(len(infix)):
if infix[i] == "(":
infix[i] = ")"
elif infix[i] == ")":
infix[i] = "("
return (infix_2_postfix("".join(infix)))[
::-1
]
if __name__ == "__main__":
Infix = input("\nEnter an Infix Equation = ")
Infix = "".join(Infix.split())
print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")