1. 栈

栈(Stack)是限制插入和删除操作只能在一个位置进行的表,该位置是表的末端,称为栈的顶(top)。栈的基本操作有PUSH(入栈)和POP(出栈)。栈又被称为LIFO(后入先出)表。

1.1 栈的实现

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 栈应用

1.2.1 检查程序中成对的符号

程序的语法错误经常是由缺少一个符号造成的。可用栈来检查符号是否成对。做一个空栈,如果字符是开放符号('({[')则将其push栈中。如果符号是个闭合符号(')]}'),则当栈空时报错,对应'()}'的错误。否则,将栈pop,如果弹出的符号不是对应的开放符号,则报错,对应'(}'的错误。文件末尾,如果栈为空,则报错,对应'({}'的错误。

def match(i,j):
opens='([{'
closes=')]}'
return opens.index(i)==closes.index(j)
def syntaxChecker(string):
stack=Stack()
balanced=True
for i in string:
if i in '([{':
stack.push(i)
elif i in ')]}':
if stack.isEmpty():
balanced=False
break
else:
j=stack.pop()
if not match(j,i):
balanced=False
break
if not stack.isEmpty():
balanced=False
return balanced

1.2.2 进制转换

十进制转换二进制:把十进制转成二进制一直分解至商数为0。从最底左边数字开始读,之后读右边的数字,从下读到上。

来自《Problem Solving with Algorithms and Data Structures》的图片:

代码:

def decimal_to_bin(dec):
stack=Stack()
cur=dec
while cur>0:
a=cur%2
cur=cur/2
stack.push(a)
binstr=''
while not stack.isEmpty():
binstr+=str(stack.pop())
return binstr

1.2.3  后缀记法

后缀记法(postfix),使用一个栈,见到一个数时入栈,遇到一个运算符时就作用于从栈弹出的两个元素,将结果弹入栈中。

(7+8)/(3+2)可以写作7 8 + 3 2 + /

来自《Problem Solving with Algorithms and Data Structures》的图片:

中缀到后缀的转换:当读到一个操作数的时候,放到输出中。读到操作符(+,-,*,/)时,如果栈为空,则压入栈中,否则弹出栈元素放到输出中直到发现优先级更低的元素为止。读到'(',压入栈中,读到')',弹出栈元素并发到输出中直到发现'('为止。在末尾,将栈元素弹出直到该栈变成空栈。

来自《Problem Solving with Algorithms and Data Structures》的图片:

def infixtoPostfix(infix):
a={}
a['*']=3
a['/']=3
a['+']=2
a['-']=2
a['(']=1
stack=Stack()
post=''
for i in infix:
if i not in a and i!=')':
post+=i
elif i=='(':
stack.push(i)
elif i==')':
top=stack.pop()
while top!='(':
post+=top
top=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 post def 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)也是表,使用队列时插入和删除在不同的端进行。队列的基本操作是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 a
else:
raise IndexError,'queue is empty'
def size(self):
return len(self.queue)

  

  

Python数据结构——栈、队列的实现(一)的更多相关文章

  1. Python数据结构——栈、队列的实现(二)

    1. 一个列表实现两个栈 class Twostacks(object): def __init__(self): self.stack=[] self.a_size=0 self.b_size=0 ...

  2. python 数据结构 - 栈

    如需转发,请注明出处:小婷儿的python https://www.cnblogs.com/xxtalhr/p/10293388.html 欢迎关注小婷儿的博客: 有问题请在博客下留言或加作者微信:t ...

  3. Python数据结构———栈

    线性数据结构 当添加一个项目时,它就被放在这样一个位置:在之前存在的项与后来要加入的项之间.像这样的数据集合常被称为线性数据结构. 栈 栈是一个项的有序集合.添加项和移除项都发生在同一“端”,这一端通 ...

  4. Python数据结构——栈的链表实现

    自定义链表实现栈的数据结构,代码如下: class Stack: def __init__(self): self._first = None def push(self,item): self._f ...

  5. Python数据结构——栈

    栈是一种特殊的列表,栈内的元素只能通过列表的一端访问,这一端称为栈顶.栈被称为一种后入先出(LIFO,last-in-first-out)的数据结构. 由于栈具有后入先出的特点,所以任何不在栈顶的元素 ...

  6. 用python实现栈/队列/双端队列/链表

    栈是元素的有序集合,添加操作与移除操作都发生在其顶端,先进后出栈操作:创建空栈,增删(顶端),查(顶端元素,元素个数,是否为空)应用:将十进制数转换成任意进制数 class Stack: # 用列表创 ...

  7. python数据结构之队列

    队列(queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表. 队列是一种先进先出的(First In First Out)的线性表,简称FIFO.允许插入的一端为队尾,允许删除的一端 ...

  8. 刚开始学python——数据结构——“自定义队列结构“

    自定义队列结构  (学习队列后,自己的码) 主要功能:用列表模拟队列结构,考虑了入队,出队,判断队列是否为空,是否已满以及改变队列大小等基本操作. 下面是封装的一个类,把代码保存在myQueue.py ...

  9. 数据结构 栈&队列

    2-4 依次在初始为空的队列中插入元素a,b,c,d以后,紧接着做了两次删除操作,此时的队头元素是( ) 删除,移动头指针: 增加,移动尾指针: 删除a,b ,队头c 2-3 在一个链队列中,fron ...

随机推荐

  1. WCF架构日记-1

    WCF功能很强大,但是真的能把其中的原理说清楚,对于我比较困难,今天对之前的笔记总结一下:     首先WCF的契约可以总结为四大类:消息契约.数据契约.服务契约.错误处理契约. [客户端处理是如何处 ...

  2. java8中的Stream

    Collection.stream() / parallelStream() 1. Stream 1)Filter    stringCollection .stream().filter((s) - ...

  3. vb6.0如何让窗体跟随鼠标运动

    首先将form的boderstyle属性设为0 Dim movesScreen As Boolean Dim mousX As Integer Dim mousY As Integer Dim cur ...

  4. MyEclipse设置编码方式 转载【http://www.cnblogs.com/susuyu/archive/2012/06/27/2566062.html】

    1.windows->Preferences……打开"首选项"对话框,左侧导航树,导航到general->Workspace, 右侧Text file encoding ...

  5. hdu 4144 状态压缩dp

    #include<map> #include<set> #include<cmath> #include<queue> #include<cstd ...

  6. Unity3d之按键

    if (Input.GetKeyDown(KeyCode.A)){ Debug.Log("您按下了A键"); } if (Input.GetKeyUp(KeyCode.A)) { ...

  7. MongoDB - The mongo Shell, Access the mongo Shell Help

    In addition to the documentation in the MongoDB Manual, the mongo shell provides some additional inf ...

  8. Part 2 How are the URL's mapped to Controller Action Methods?

    Part 2 How are the URL's mapped to Controller Action Methods? The answer is ASP.NET Routing.Notice t ...

  9. Python Tool Visual Studio简单使用

    由于一直在做.NET的开发,一直用的IDE是VS系列的,所以想用VS也能开发Python,刚好微软提供一个插件PTVS(Python Tool Visual Studio)专门应用于Python开发的 ...

  10. centos安装与基本使用

    1.      插入安装光盘 2.      进入试用 3.      在试用的桌面系统选择安装到硬盘 4.      选择安装语言 5.      选择基本存储或者专门的存储设备 6.      - ...