s = Stack()print(s.isEmpty())
s.push(4)
s.push('dog')print(s.peek())
s.push(True)print(s.size())print(s.isEmpty())
s.push(8.4)print(s.pop())print(s.pop())print(s.size())
True
dog
3
False
8.4
True
2
2、使用栈来判断一个括号是否是正确匹配的
例如:(()()()())、(((())))、(()((())()))等是正确的,()))是错误的
defparChecker(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 = index +1if balanced and s.isEmpty():returnTrueelse:returnFalseprint(parChecker('((()))'))print(parChecker('(()'))
True
False
3、括号匹配一个更广泛的应用,匹配对象不仅包含小括号,还包括中括号,大括号等
例如:{ { ( [ ] [ ] ) } ( ) }
defparChecker(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:returnFalsedefmatches(open, close):
opens ="([{"
closers =")]}"return opens.index(open)== closers.index(close)
Create an empty stack called opstack for keeping operators. Create an empty list for output.
Convert the input infix string to a list by using the string method split.
Scan the token list from left to right.
If the token is an operand, append it to the end of the output list.
If the token is a left parenthesis, push it on the opstack.
If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each operator to the end of the output list.
If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the opstack that have higher or equal precedence and append them to the output list.
When the input expression has been completely processed, check the opstack. Any operators still on the stack can be removed and appended to the end of the output list.
print(infixToPostfix("A * B + C * D"))print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )"))print(infixToPostfix("( A + B ) * ( C + D )"))print(infixToPostfix("( A + B ) * C"))print(infixToPostfix("A + B * C"))
A B * C D * +
A B + C * D E - F G + * -
A B + C D + *
A B + C *
A B C * +
5.2、后缀表达式计算
计算 456*+ = ?
defpostfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()# print(tokenList)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)return operandStack.pop()defdoMath(op, op1, op2):if op =="*":return op1 * op2
elif op =="/":return op1 / op2
elif op =="+":return op1 + op2
else:return op1 - op2