def build_parse_tree(fp_expr): fp_list = fp_expr.split() p_stack = Stack() expr_tree = BinaryTree("") p_stack.push(expr_tree) current_tree = expr_tree for i in fp_list: if i == "(": current_tree.insert_left("") p_stack.push(current_tree) current_tree = current_tree.left_child elif i in ["+", "-", "*", "/"]: current_tree.root = i current_tree.insert_right("") p_stack.push(current_tree) current_tree = current_tree.right_child elif i == ")": current_tree = p_stack.pop() elif i not in ["+", "-", "*", "/", ")"]: try: current_tree.root = int(i) parent = p_stack.pop() current_tree = parent except ValueError: raise ValueError("token '{}' is not a valid integer".format(i)) return expr_tree
def par_checker(symbol_string): s = Stack() for symbol in symbol_string: if symbol == "(": s.push(symbol) else: if s.is_empty(): return False else: s.pop() return s.is_empty()
def postfix_eval(postfix_expr): operand_stack = Stack() token_list = postfix_expr.split() for token in token_list: if token in "0123456789": operand_stack.push(int(token)) else: operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = do_math(token, operand1, operand2) operand_stack.push(result) return operand_stack.pop()
def to_str(n, base): r_stack = Stack() convert_string = "0123456789ABCDEF" while n > 0: if n < base: r_stack.push(convert_string[n]) else: r_stack.push(convert_string[n % base]) n = n // base res = "" while not r_stack.is_empty(): res = res + str(r_stack.pop()) return res
def revstring(mystr): s = Stack() for c in mystr: s.push(c) revstr = "" while not s.is_empty(): revstr += s.pop() return revstr
def divide_by_2(dec): s = Stack() while dec > 0: rem = dec % 2 s.push(rem) dec = dec // 2 bin = "" while not s.is_empty(): bin += str(s.pop()) return bin
def base_converter(decimal_num, base): s = Stack() digits = "0123456789ABCDEF" while decimal_num > 0: rem = decimal_num % base s.push(rem) decimal_num = decimal_num // base new_str = "" while not s.is_empty(): new_str += digits[s.pop()] return new_str
def infix_to_postfix(infix_expr): prec = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1} op_stack = Stack() postfix_list = [] token_list = infix_expr.split() for token in token_list: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 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 (prec[op_stack.peek()] >= prec[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)