def infix_to_postfix(expression): operator_stack = Stack() output = [] token_list = expression.split() precedence = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1} chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for token in token_list: try: int(token) number = True except ValueError: number = False if token in chars or number: output.append(token) elif token == "(": operator_stack.add(token) elif token == ")": stack_token = operator_stack.pop() while stack_token != "(": output.append(stack_token) stack_token = operator_stack.pop() else: while (not operator_stack.is_empty()) and \ (precedence[operator_stack.peek()] >= precedence[token]): output.append(operator_stack.pop()) operator_stack.add(token) while not operator_stack.is_empty(): output.append(operator_stack.pop()) return " ".join(output)
def base_converter(number, base): num_stack = Stack() values = "0123456789ABCDEFGHIJKLMOPQ" while number > 0: num_stack.add(number % base) number = number // base converted_number = "" while not num_stack.is_empty(): converted_number += values[num_stack.pop()] return converted_number
class SortedStack(Stack): def __init__(self): super().__init__() self._temp = Stack() def push(self, value): if not self.is_empty(): while not self.is_empty() and self.peek() < value: self._temp.push(self.pop()) super().push(value) self._unload_temp() def _unload_temp(self): while not self._temp.is_empty(): super().push(self._temp.pop())