def postfix_eval(postfix_expr): op_stack = ArrayStack() token_list = postfix_expr.split() for token in token_list: if token in "0123456789": op_stack.push(int(token)) else: operand2 = op_stack.pop() operand1 = op_stack.pop() result = do_math(token, operand1, operand2) op_stack.push(result) return op_stack.pop()
def par_checker(symbol_str): s = ArrayStack() balanced = True index = 0 while index < len(symbol_str) and balanced: symbol = symbol_str[index] if symbol == "(": s.push(symbol) else: if s.is_empty(): balanced = False else: s.pop() index = index + 1 if balanced and s.is_empty(): return True else: return False
def divide_by2(num): remstack = ArrayStack() while num > 0: rem = num % 2 remstack.push(rem) num = num // 2 bin_str = "" while not remstack.is_empty(): bin_str = bin_str + str(remstack.pop()) return bin_str
def base_converter(num, base): digits = "0123456789ABCDEF" remstack = ArrayStack(max_size=1024) while num > 0: rem = num % base remstack.push(rem) num = num // base new_str = "" while not remstack.is_empty(): new_str = new_str + digits[remstack.pop()] return new_str
def par_checker2(symbol_str): s = ArrayStack() balanced = True index = 0 while index < len(symbol_str) and balanced: symbol = symbol_str[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 = index + 1 if balanced and s.is_empty(): return True else: return False
def test_array_stack(): s = ArrayStack(3) s.push(1) s.push(2) s.push(3) assert len(s) == 3 with pytest.raises(Exception) as excinfo: s.push(4) assert 'full' in str(excinfo) assert s.pop() == 3 assert not s.is_empty() assert s.pop() == 2 assert s.pop() == 1 with pytest.raises(Exception) as excinfo: s.pop() assert 'empty' in str(excinfo) assert s.is_empty() assert len(s) == 0
def infix_to_postfix(infix_expr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = ArrayStack() 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 == ")": topToken = op_stack.pop() while topToken != "(": postfix_list.append(topToken) topToken = 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)