本程序是MOOC學習北京大學陳斌老師課程後,自行改進編寫。歡迎你們交流探討,不斷學習進步python
程序流程:
括號匹配算法:
1.輸入括號表達式
2.若是是左括號的話入棧
3.若是遇到右括號,可是沒有左括號與其匹配(棧爲空),則括號不匹配
4.若是遇到了右括號且棧不爲空,判斷右括號和左括號的類型是否一致(好比中括號"[「與」]「匹配,」[「與」)"不匹配),不一致則括號不匹配
5.若是遇到其餘字符,就不予處理
6.當括號表達式字符循環結束,棧是空的,則括號匹配;若是棧是非空的,則括號不匹配
算法
源程序.app
from Teststack import Stack def bracMatch(bracketItem): bracketList = list(bracketItem) braStack = Stack() leftbrac = "{[(" rightbrac = "}])" result = True for item in bracketList: if item in leftbrac: braStack.push(item) elif item in rightbrac: if braStack.isEmpty(): result = False else: if matchBoth(braStack.peek(),item): braStack.pop() else: result = False if braStack.isEmpty() and result: result = True else: result = False return result def matchBoth(item1,item2): leftbrac = "{[(" rightbrac = "}])" return leftbrac.index(item1) == rightbrac.index(item2) if __name__ == "__main__": str = input("請輸入表達式") if bracMatch(str): print("括號匹配") else: print("括號不匹配")
棧的定義類文件Teststack.py學習
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items)
輸出結果spa