''' 匹配括号 '''defperChecker(symbolString):
s = Stack()
balanced =True
index =0while index <len(symbolString)and balanced:
symbol = symbolString[index]if symbol =="(":
s.push(symbol)else:if s.isEmpty():
balanced =Falseelse:
s.pop()
index +=1if balanced and s.isEmpty():returnTrueelse:returnFalseprint(perChecker("(()(((()))))"))# True
''' 匹配符号 '''defmatches(open,close):
opens ="([{"
closers =")]}"return opens.index(open)== closers.index(close)defperChecker_(symbolString):
s = Stack()
balanced =True
index =0while index <len(symbolString)and balanced:
symbol = symbolString[index]if symbol in"([{":
s.push(symbol)else:if s.isEmpty():
balanced =Falseelse:
top = s.pop()ifnot matches(top,symbol):
balanced =False
index +=1if balanced and s.isEmpty():returnTrueelse:returnFalseprint(perChecker_("[(){}({[]})]"))
''' 十进制转换为其他进制 '''defbaseConverter(decNumber,base):
remstack = Stack()while decNumber >0:
rem = decNumber % base
remstack.push(rem)
decNumber //= base
baseString =""whilenot remstack.isEmpty():if(remstack.peek()>9):
baseString +=str(chr(remstack.pop()+55))'''
亦可使用一个字符串包含所有的字符,以栈顶端作为下标对应
'''else:
baseString +=str(remstack.pop())return baseString
print(baseConverter(15,16))
''' 中序表达式转换成后序转换式 '''import string
definfixToPostfix(infixexpr):
prec ={}
prec["*"]= prec["/"]=3
prec["+"]= prec["-"]=2
prec["("]=1
opStack = Stack()
postfixList =[]
tokenList = infixexpr.split()for token in tokenList:if token in string.ascii_uppercase:
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)print(infixToPostfix("( A + B ) * ( C + D )"))
''' 后序运算式的运算 '''defpostfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()for token in tokenList:if token in"0123456789":
operandStack.push(int(token))else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)defdoMath(op,op1,op2):if op =="*":return op1 * op2
elif op =="/":return op1 / op2
elif op =="+":return op1 + op2
else:return op1 - op2