Skip to content

Instantly share code, notes, and snippets.

@hamzamuric
Last active April 14, 2018 22:42
Show Gist options
  • Save hamzamuric/45e7505e8ecec1d03064d3550a7282d2 to your computer and use it in GitHub Desktop.
Save hamzamuric/45e7505e8ecec1d03064d3550a7282d2 to your computer and use it in GitHub Desktop.
Program to convert mathematical expressions into postfix notation
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