1 defcheck_parens(text) :2 #括号匹配检查函数,text 是被检查的正文串
3 parens = "(){}[]"
4 open_parens = "({["
5 opposite = {")":"(", "}":"{", "]":"["}6
7 defparentheses(text) :8 #括号生成器,每次调用返回text里的下一括号及其位置
9 i.text_len =0,len(text)10 whileTrue :11 while i < text_len and text[i] not inparens :12 i += 1
13 if i >=text_len :14 return
15 yieldtext[i],i16 i += 1
17
18 st = SStack() #创建栈 st
19
20 for pr , i in parentheses(text) : #对text里各括号和位置迭代
21 if pr in open_parens : #开括号,压栈并继续
22 st.push(pr)23 elif st.pop() != opposite[pr] : #闭括号 若匹配失败就退出
24 print("Unmatching is found at",i,"for",pr)25 returnFalse26 #else : 匹配成功什么也不做