一旦认识到用栈来保存括号是合理的,算法编写起来就会十分容易。由一个空栈开始,从左 往右依次处理括号。如果遇到左括号,便通过 push 操作将其加入栈中,以此表示稍后需要有一 个与之匹配的右括号。反之,如果遇到右括号,就调用 pop 操作。只要栈中的所有左括号都能 遇到与之匹配的右括号,那么整个括号串就是匹配的;如果栈中有任何一个左括号找不到与之匹 配的右括号,则括号串就是不匹配的。在处理完匹配的括号串之后,栈应该是空的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 括号匹配 defparChecker(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol == "(": s.push(symbol) else: if s.isEmpty(): balanced = False else: s.pop() index += 1 if balanced and s.isEmpty(): returnTrue else: returnFalse
defparChecker(symbolString): i = 1 s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol in"{[(": s.push(symbol)
else: if s.isEmpty(): balanced = False else: top = s.pop()
ifnot matches(top,symbol): balanced = False index += 1
if balanced and s.isEmpty(): returnTrue else: returnFalse
defmatches(left,right):
lefts = "([{" rights = ")]}" return lefts.index(left) == rights.index(right)
defdivide_to_2(num): s = Stack() binStr = "" while num > 0: s.push(num % 2) num = num // 2 whilenot s.isEmpty(): binStr = binStr + str(s.pop()) return binStr
num = int(input('输入数字:')) print(divide_to_2(num))
十进制— > 任意进制
1 2 3 4 5 6 7 8 9 10 11 12
defdivide_to_base(num,base): s = Stack() baseStr = "" while num > 0: s.push(num % base) num = num // base whilenot s.isEmpty(): baseStr = baseStr + str(s.pop()) return baseStr
for token in expression_list: if token.isdigit(): op_stack.push(int(token)) else: if token == '@': break op = token op2 = op_stack.pop() op1 = op_stack.pop() result = do_math(op, op1, op2) op_stack.push(result)
return op_stack.pop()
defdo_math(op, op1, op2): if op == "+": return op1 + op2 elif op == "-": return op1 - op2 elif op == "*": return op1 * op2 elif op == "/": if op2 == 0: return"error" return op1 / op2
if __name__ == '__main__': print(calc_postfix_expression(S))