defmatches(top, symbol):
openingSymbols ="({["
closingSymbols =")}]"return openingSymbols.index(top)== closingSymbols.index(symbol)defcheckSymbolBalance(inputStr):
symbolstack = Stack()for symbol in inputStr:if symbol in["(","{","["]:
symbolstack.push(symbol)elif symbol in[")","}","]"]:if symbolstack.isEmpty():returnFalseelse:
topSymbol = symbolstack.pop()ifnot matches(topSymbol, symbol):returnFalsereturn symbolstack.isEmpty()assert( checkSymbolBalance("000[000[")==False)assert( checkSymbolBalance("000]000[")==False)assert( checkSymbolBalance("000]000]")==False)assert( checkSymbolBalance("000[000]")==True)assert(checkSymbolBalance("{{([][])}()}")==True)
2. 中缀表达式改后缀表达式
definfixToPostfix(infixexpr):
prec ={}
prec["*"]=3
prec["/"]=3
prec["+"]=2
prec["-"]=2
prec["("]=1
opStack = Stack()
postfixList =[]
tokenList = infixexpr.split()for token in tokenList:if token in"ABCDEFGHIJKLMNOPQRSTUVWXYZ"or token in"0123456789":
postfixList.append(token)elif token =='(':
opStack.push(token)elif token ==')':
topToken = opStack.pop()while topToken !='(':
postfixList.append(topToken)
topToken = opStack.pop()else:while(not opStack.isEmpty())and(prec[opStack.peek()]>= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)whilenot opStack.isEmpty():
postfixList.append(opStack.pop())return" ".join(postfixList)assert(infixToPostfix("A * B + C * D")=="A B * C D * +")assert(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )")=="A B + C * D E - F G + * -")