def infix_to_postfix(infix_expr): precedence = {} precedence["*"] = 3 precedence["/"] = 3 precedence["+"] = 2 precedence["-"] = 2 precedence["("] = 1 op_stack = Stack() postfix_list = [] token_list = infix_expr.split() for token in token_list: if token in "ABCDEFGHIJKLLMNOPQRSTUVWXYZ" or token in "0123456789": postfix_list.append(token) elif token == '(': op_stack.push(token) elif token == ')': top_token = op_stack.pop() while top_token != '(': postfix_list.append(top_token) top_token = op_stack.pop() else: while (not op_stack.is_empty()) and (precedence[op_stack.peek()] >= precedence[token]): postfix_list.append(op_stack.pop()) op_stack.push(token) while not op_stack.is_empty(): postfix_list.append(op_stack.pop()) return "".join(postfix_list)
def par_checker(symbol_string): s = Stack() balanced = True index = 0 while index < len(symbol_string) and balanced: symbol = symbol_string[index] if symbol in '([{': s.push(symbol) else: if s.is_empty(): balanced = False else: top = s.pop() if not matches(top, symbol): balanced = False index += 1 return balanced and s.is_empty()
def par_checker(symbol_string): s = Stack() balanced = True index = 0 while index < len(symbol_string) and balanced: symbol = symbol_string[index] if symbol == '(': s.push(symbol) else: if s.is_empty(): balanced = False else: s.pop() index += 1 return balanced and s.is_empty()
def divide_by_2(dec_number): rem_stack = Stack() while dec_number > 0: rem = dec_number % 2 rem_stack.push(rem) dec_number //= 2 # // integer division bin_string = "" while not rem_stack.is_empty(): bin_string += str(rem_stack.pop()) return bin_string
def base_converter(dec_number, base): rem_stack = Stack() while dec_number > 0: rem = dec_number % base rem_stack.push(rem) dec_number //= base # // integer division base_string = "" while not rem_stack.is_empty(): base_string += str(rem_stack.pop()) return base_string