Python数据结构——栈、队列的实现(一)
1. 棧
棧(Stack)是限制插入和刪除操作只能在一個位置進(jìn)行的表,該位置是表的末端,稱為棧的頂(top)。棧的基本操作有PUSH(入棧)和POP(出棧)。棧又被稱為LIFO(后入先出)表。
1.1 棧的實現(xiàn)
class Stack(object):def __init__(self):self.stack=[]def isEmpty(self):return self.stack==[]def push(self,item):self.stack.append(item)def pop(self):if self.isEmpty():raise IndexError,'pop from empty stack'return self.stack.pop()def peek(self):return self.stack[-1]def size(self):return len(self.stack)1.2 棧應(yīng)用
1.2.1 檢查程序中成對的符號
程序的語法錯誤經(jīng)常是由缺少一個符號造成的。可用棧來檢查符號是否成對。做一個空棧,如果字符是開放符號('({[')則將其push棧中。如果符號是個閉合符號(')]}'),則當(dāng)棧空時報錯,對應(yīng)'()}'的錯誤。否則,將棧pop,如果彈出的符號不是對應(yīng)的開放符號,則報錯,對應(yīng)'(}'的錯誤。文件末尾,如果棧為空,則報錯,對應(yīng)'({}'的錯誤。
?
def match(i,j):opens='([{'closes=')]}'return opens.index(i)==closes.index(j) def syntaxChecker(string):stack=Stack()balanced=Truefor i in string:if i in '([{':stack.push(i)elif i in ')]}':if stack.isEmpty():balanced=Falsebreakelse:j=stack.pop()if not match(j,i):balanced=Falsebreakif not stack.isEmpty():balanced=Falsereturn balanced1.2.2 進(jìn)制轉(zhuǎn)換
十進(jìn)制轉(zhuǎn)換二進(jìn)制:把十進(jìn)制轉(zhuǎn)成二進(jìn)制一直分解至商數(shù)為0。從最底左邊數(shù)字開始讀,之后讀右邊的數(shù)字,從下讀到上。
來自《Problem Solving with Algorithms and Data Structures》的圖片:
代碼:
def decimal_to_bin(dec):stack=Stack()cur=decwhile cur>0:a=cur%2cur=cur/2stack.push(a)binstr=''while not stack.isEmpty():binstr+=str(stack.pop())return binstr1.2.3 ?后綴記法
后綴記法(postfix),使用一個棧,見到一個數(shù)時入棧,遇到一個運算符時就作用于從棧彈出的兩個元素,將結(jié)果彈入棧中。
(7+8)/(3+2)可以寫作7 8 + 3 2 + /
來自《Problem Solving with Algorithms and Data Structures》的圖片:
?中綴到后綴的轉(zhuǎn)換:當(dāng)讀到一個操作數(shù)的時候,放到輸出中。讀到操作符(+,-,*,/)時,如果棧為空,則壓入棧中,否則彈出棧元素放到輸出中直到發(fā)現(xiàn)優(yōu)先級更低的元素為止。讀到'(',壓入棧中,讀到')',彈出棧元素并發(fā)到輸出中直到發(fā)現(xiàn)'('為止。在末尾,將棧元素彈出直到該棧變成空棧。
來自《Problem Solving with Algorithms and Data Structures》的圖片:
?
def infixtoPostfix(infix):a={}a['*']=3a['/']=3a['+']=2a['-']=2a['(']=1stack=Stack()post=''for i in infix:if i not in a and i!=')':post+=ielif i=='(':stack.push(i)elif i==')':top=stack.pop()while top!='(':post+=toptop=stack.pop()else: while not stack.isEmpty() and a[i]<=a[stack.peek()]:post+=stack.pop()stack.push(i)while not stack.isEmpty():post+=stack.pop()return postdef postfixExp(postfix):stack=Stack()postlist=postfix.split()for i in postlist:if i not in '+-*/':stack.push(i)else:a=stack.pop()b=stack.pop()result=math(i,b,a)stack.push(result)return stack.pop() def math(x,y,z):if x=='+':return float(y)+float(z)if x=='-':return float(y)-float(z)if x=='*':return float(y)*float(z)if x=='/':return float(y)/float(z)2 隊列
隊列(queue)也是表,使用隊列時插入和刪除在不同的端進(jìn)行。隊列的基本操作是Enqueue(入隊),在表的末端(rear)插入一個元素,還有出列(Dequeue),刪除表開頭的元素。
class Queue(object):def __init__(self):self.queue=[]def isEmpty(self):return self.queue==[]def enqueue(self,x):self.queue.append(x)def dequeue(self):if self.queue:a=self.queue[0]self.queue.remove(a)return aelse:raise IndexError,'queue is empty'def size(self):return len(self.queue)
總結(jié)
以上是生活随笔為你收集整理的Python数据结构——栈、队列的实现(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 给文本框添加模糊搜索功能(“我记录”MV
- 下一篇: SSH框架中不为人知的细节(一)