Python数据结构:栈的应用
【Python數(shù)據(jù)結(jié)構(gòu)1】棧的應(yīng)用
棧Stack:什么是棧?
?一種有次序的數(shù)據(jù)項(xiàng)集合,在棧中,數(shù)據(jù)項(xiàng)的加入和移除都僅發(fā)生在同一端
這一端叫棧“頂top”,另一端叫棧“底base”
?日常生活中有很多棧的應(yīng)用,如:盤子、托盤、書堆等等
?距離棧底越近的數(shù)據(jù)項(xiàng),留在棧中的時(shí)間就越長,而最新加入棧的數(shù)據(jù)項(xiàng)會被最先移除
?這種次序通常稱為后進(jìn)先出LIFO:Last in First out
這是一種基于數(shù)據(jù)項(xiàng)保存時(shí)間的次序,時(shí)間越短的離棧頂越近,而時(shí)間越長的離棧底越近
???抽象數(shù)據(jù)類型“棧”定義為如下的操作:
Stack():創(chuàng)建一個(gè)空棧,不包含任何數(shù)據(jù)項(xiàng)
push(item):將item加入棧頂,無返回值
pop():將棧頂數(shù)據(jù)項(xiàng)移除,并返回,棧被修改
peek():“窺視”棧頂數(shù)據(jù)項(xiàng),返回棧頂?shù)臄?shù)據(jù)項(xiàng)但不移除,棧不被修改
isEmpty():返回棧是否為空棧
size():返回棧中有多少個(gè)數(shù)據(jù)項(xiàng)
抽象數(shù)據(jù)類型Stack:操作樣例
另外
python列表(list)就具有棧的特性,其函數(shù)與棧中相對應(yīng)的函數(shù)功能類似,故可以直接把list當(dāng)做棧來使用,也可以利用list構(gòu)建Stack類
棧代碼示例
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)示例1:進(jìn)制轉(zhuǎn)換
直接使用list做為棧
def HexConv(decNumber,base):dights=[str(i) for i in range(10)]+[chr(i) for i in range(65,72)]remstack=[]while decNumber>0:rem=decNumber%baseremstack.append(dights[rem])decNumber//=baseres=""while remstack!=[]:res+=remstack.pop()return resif __name__ == '__main__':n=int(input("請輸入原數(shù):"))hex=int(input("目標(biāo)進(jìn)制:"))print("十進(jìn)制{}轉(zhuǎn)換為{}進(jìn)制結(jié)果:{}".format(n,hex,HexConv(n,hex)))示例2:括號匹配
引入Stack類
from stack_set import Stackdef bracMatch(bracketItem):bracketList = list(bracketItem)braStack = Stack()leftbrac = "{[("rightbrac = "}])"result = Truefor item in bracketList:if item in leftbrac:braStack.push(item)elif item in rightbrac:if braStack.isEmpty():result = Falseelse:# peek函數(shù)取棧頂元素,判斷棧頂元素是否跟右括號相對應(yīng)if matchBoth(braStack.peek(), item):braStack.pop()else:result = Falseif braStack.isEmpty() and result:result = Trueelse:result = Falsereturn resultdef matchBoth(item1, item2):leftbrac = "{[("rightbrac = "}])"return leftbrac.index(item1) == rightbrac.index(item2)if __name__ == "__main__":str = input("請輸入表達(dá)式")if bracMatch(str):print("括號匹配")else:print("括號不匹配")示例3:中綴表達(dá)式轉(zhuǎn)為后綴表達(dá)式
from stack_set import Stackdef infixToPostfix(infixpr):pre={}pre['*'],pre['/']=3,3pre['+'],pre['-']=2,2pre['(']=1charlist=[chr(i) for i in range(65,91)]numlist=[i for i in range(10)]# 生成一個(gè)用于存儲符號的棧和一個(gè)用于存儲值的列表opstack=Stack()postfixlist=[]items=infixpr.split()for item in items:# 判斷是否為表達(dá)式中的值if item in charlist or item in numlist:postfixlist.append(item)elif item=="(":opstack.push(item)elif item==')':tokentop=opstack.pop()while tokentop!="(":postfixlist.append(tokentop)tokentop=opstack.pop()else:# 當(dāng)棧非空時(shí),入棧的符號要先檢查其是否滿足入棧優(yōu)先級while(not opstack.isEmpty()) and (pre[item]<=pre[opstack.peek()]):postfixlist.append(opstack.pop())opstack.push(item)print("stack:{},postlist:{}".format(opstack.items,postfixlist))# 最后將棧中元素出棧(進(jìn)棧前已考慮優(yōu)先級,出棧直接出)while not opstack.isEmpty():postfixlist.append(opstack.pop())return "".join(postfixlist) if __name__ == '__main__':infix="A + ( B * C )"postfix=infixToPostfix(infix)print("其對應(yīng)的后綴表達(dá)式:{}".format(postfix))讀者可自行體會直接使用list與構(gòu)建stack的區(qū)別
參考:MOOC陳斌老師
總結(jié)
以上是生活随笔為你收集整理的Python数据结构:栈的应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 关联规则挖掘,数据挖掘实验
- 下一篇: 《Python数据分析与挖掘实战》第8章