python栈之多符号类型的匹配

 1 from pythonds import Stack
 2 def parChecker(symbolString):
 3     s = Stack()
 4     balanced = True   #声明一个布尔变量
 5     index = 0
 6     while index < len(symbolString) and balanced:  #len函数定下标
 7         symbol = symbolString[index]
 8         if symbol in "([{":     #开括号压入栈,注意字符串与子串的特性
 9             s.push(symbol)
10         else:
11             if s.isEmpty():
12                 balanced = False
13             else:
14                 top = s.pop()   
15                 if not matches(top,symbol):   #将栈中待删除的顶部元素与字符串中下一个待与之匹配的右闭符号比较
16                     balanced = False
17         index = index + 1
18     if balanced and s.isEmpty():      #python中if convention即if convention  is True!!注意此行的位置,与while并列
19         return True
20     else:
21         return False
22 def matches(open,close):
23     opens = "([{"                     #开括号,待压入栈
24     closers = ")]}"                   #闭括号  待与栈匹配后一起删除
25     return opens.index(open) == closers.index(close)   #输出的是布尔值,str1.index(str2)输出子串str2在str1中的起始位置

 

posted @ 2018-10-12 00:46  Parallax  阅读(217)  评论(0编辑  收藏  举报