Last active
April 14, 2018 22:42
-
-
Save hamzamuric/45e7505e8ecec1d03064d3550a7282d2 to your computer and use it in GitHub Desktop.
Program to convert mathematical expressions into postfix notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
operators = {'(': 0, ')': 0, '+': 1, '-': 1, '*': 2, '/': 2, '%': 2} | |
stack = [] | |
postfix = [] | |
expression = input('Enter your expression: ').split() | |
for ch in expression: | |
if ch in operators: | |
if ch is ')': | |
while stack and stack[-1] is not '(': | |
postfix.append(stack.pop()) | |
stack.pop() | |
continue | |
# if stack and operators[ch] <= operators[stack[-1]]: | |
if stack and operators[stack[-1]] is 2 and (operators[ch] is 2 or operators[ch] is 1): | |
postfix.append(stack.pop()) | |
stack.append(ch) | |
else: | |
postfix.append(ch) | |
for _ in range(len(stack)): | |
postfix.append(stack.pop()) | |
output = ''.join(str(e) for e in postfix) | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment