Created
March 21, 2023 06:26
-
-
Save Abdur-rahmaanJ/9f5ecddfe5a00f0e4ea8c4abbb4cd921 to your computer and use it in GitHub Desktop.
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
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