from pythonds.basic.stack import Stack
"""
1、先建立一个空栈 s
2、设一个为True的变量 balanced
3、定义一个为0的int对象 index
4、求传来的参数长度大于0,且balanced为true
5、先求参数的第零个索引,如果这个索引为"(" 就放入栈中,
如果不是"(",就判断栈s是否为空
如果为空,就另balanced变量为False
不为空,就删除栈顶的元素,
然后在判断第二个索引值,就要给index加上1
全部遍历完后,判断balanced是否为true和栈s是否为空
如果两者都成立,则返回true
不成立,则返回false
"""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('((((()))))))'))print(parChecker('((()))'))str="123456789"ifstr[2]in'356589':print("包含")else:print("不包含")print(str.index("5"))
from pythonds.basic.stack import Stack
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 = index +1if balanced and s.isEmpty():returnTrueelse:returnFalsedefmatches(open, close):
opens ="([{"
closes =")]}"return opens.index(open)== closes.index(close)print(parChecker('{[()]}'))