Skip to content

Instantly share code, notes, and snippets.

@Abdur-rahmaanJ
Created March 21, 2023 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abdur-rahmaanJ/9f5ecddfe5a00f0e4ea8c4abbb4cd921 to your computer and use it in GitHub Desktop.
Save Abdur-rahmaanJ/9f5ecddfe5a00f0e4ea8c4abbb4cd921 to your computer and use it in GitHub Desktop.
tokens = ['111', '+', '2', '+', '(', '33', '**', '2', ')', '-', '1', '*', '1']
# 111 2 + 33 2 ^ + 1 1 * -
def is_number(num):
# quick way
return (num[0] in '0123456789')
def to_postfix(tokens):
operators = {
'**': 3,
'*': 2,
'/': 2,
'+': 1,
'-': 1
}
output_queue = []
operator_stack = []
for t in tokens:
if is_number(t):
output_queue.append(t)
elif t in operators:
if operator_stack:
on_top = operator_stack[-1]
if on_top == '(':
operator_stack.append(t)
elif operators[on_top] >= operators[t]:
output_queue.append(operator_stack.pop())
operator_stack.append(t)
else:
operator_stack.append(t)
else:
operator_stack.append(t)
elif t == '(':
operator_stack.append(t)
elif t == ')':
while operator_stack:
on_top = operator_stack[-1]
if on_top == '(':
operator_stack.pop()
break
else:
output_queue.append(operator_stack.pop())
while operator_stack:
output_queue.append(operator_stack.pop())
return output_queue
print(to_postfix(tokens))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment