def eval_infix(infix_exp): operands = Stack() op_stack = Stack() infix = infix_exp.split() for sym in infix: if sym.isdigit(): operands.push(sym) elif sym == "(": op_stack.push(sym) elif sym == ")": second = float(operands.pop()) first = float(operands.pop()) op = op_stack.pop() operands.push(operators[op](first, second)) op_stack.pop() elif sym in operators.keys(): if not op_stack.isEmpty() and precedence[op_stack.peek()] >= precedence[sym]: op = op_stack.pop() second = float(operands.pop()) first = float(operands.pop()) operands.push(operators[op](first, second)) op_stack.push(sym) while not operands.size() == 1: second = float(operands.pop()) first = float(operands.pop()) op = op_stack.pop() operands.push(operators[op](first, second)) return operands.pop()
def infix_to_postfix(infix_exp): operators = Stack() infix_exp = infix_exp.split() postfix = [] for sym in infix_exp: if sym in string.ascii_letters or sym.isdigit(): postfix.append(sym) elif sym == "(": operators.push(sym) elif sym == ")": while not operators.peek() == "(": postfix.append(operators.pop()) operators.pop() elif sym in precedence.keys(): while not operators.isEmpty() and precedence[operators.peek()] >= precedence[sym]: postfix.append(operators.pop()) operators.push(sym) else: raise TypeError("Wrong expression") while not operators.isEmpty(): postfix.append(operators.pop()) return " ".join(postfix)
def general_parentheses_checker(expression): sym_dict = {')':'(', '}': '{', ']': '['} s = Stack() for symbol in expression: if symbol in '([{': s.push(symbol) elif symbol in ')]}': if s.isEmpty(): return False else: if sym_dict[symbol] == s.peek(): s.pop() else: return False if s.isEmpty(): return True else: return False