用列表构建stack 和 队列
来源:互联网 发布:linux系统克隆 编辑:程序博客网 时间:2024/05/16 11:36
最近对Python 颇感兴趣,买回来两本书《Python 核心编程》 和《利用Python进行数据分析》 开始学习。
学习联系实践,这样效果最好,同时也想记载下我的学习历程,所以开通了csdn的博客。
下面就把书上讲到的用列表实现堆栈和队列的例子拿出来分享。
</pre></p><p> 1-用列表模拟堆栈。</p><p><pre name="code" class="html" style="white-space: pre;">stack = []def InPush(): stack.append((raw_input('Enter your String to push in : ' )).strip()) def OutPop(): if len(stack) == 0: print 'Sorry ,your stack is empty,can not pop out any information' else: print ' Romove [', `stack.pop()` , ']'def ViewStack(): print stackCMDs = {'i':InPush ,'o':OutPop, 'v':ViewStack}def showmenu(): printmessege=''' (i)nPush (o)utPop (v)iew (q)uit Enter you choice : ''' while True: while True: try : choice = raw_input(printmessege).strip()[0].lower() except(EOFError,KeyboardInterrupt,IndexError): choice = 'q' print ' \n your choice is :[%s]' % choice if choice not in printmessege: print 'Invalid choice ,Please look tips carfully!' else: break if choice == 'q': break else: CMDs[choice]() if __name__ == '__main__': showmenu()
2-列表实现队列结构
<pre name="code" class="python">queue = []def enQ(): queue.append(raw_input('Enter New string: ').strip())def deQ(): if len(queue) == 0: print 'Cannot pop from an empty queue' else: print 'Remove [',`queue.pop(0)`,']'def viewQ(): print queueCMDs = {'e': enQ, 'd':deQ, 'v': viewQ}def showmenu(): pr = ''' (E)nqueue (D)equeue (V)iew (Q)uit Enter choice: ''' while True: while True: try: choice = raw_input(pr).strip()[0].lower() except (EOFError,KeyboardInterrupt,IndexError): choice = 'q' print '\n You picked: [%s]' %choice if choice not in 'devq': print 'Invalid option ,try again' else: break if choice == 'q': break CMDs[choice]()if __name__ == '__main__': showmenu()
对于以上的两段代码,分别体现出了堆栈和队列的结构特点:堆栈先进后出,所以在str.pop()参数不写,默认就是弹出最后的元素,而队列是先进先出,所以str.pop(0),先出第一个元素。
0 0
- 用列表构建stack 和 队列
- 栈Stack和队列Queue
- 栈Stack和队列Queue
- 用标签显示用户列表及Value Stack和Stack Context
- 栈(Stack)和队列(Queue)
- C++栈和队列(stack,queue,priority_queue)
- Stack and Queue 栈和队列
- python实现stack(栈)和队列(queue)
- f-stack 队列和进程关系
- JS中的队列(queue)和栈(stack)
- C_栈和队列----stack堆栈容器
- Java实现栈Stack和队列Queue
- 堆、列表、队列和栈
- 自定义数组列表和队列
- 用Python中的列表模拟栈和队列
- 用mongodb构建延时队列
- 用mongodb构建延时队列
- Java实现数据结构栈stack和队列Queue
- 【秀优越(xie e)】原来出题也可以这么恶心。
- 前端开发的基础学习与练习
- 3.15
- POJ 3264 RMQ模版
- 响应者链
- 用列表构建stack 和 队列
- 今天本地调试的时候出现几次com.mchange.v2.resourcepool.CannotAcquireResourceException:
- CPU的利用率是怎么计算的
- 软件测试面试
- LeetCode - Plus One - Frequent
- 监听网络的广播接收者接收两次解决方案
- 前端面试需要掌握的一些知识点
- UVA - 10306 e-Coins
- PE 6 Sum square difference