python模拟队列和堆栈(列表练习)

##################################queue#########################################
#!/usr/bin/env python

‘use list as a queue‘

#define a void list as a void queue
queue = []

#define in queue function
def enQ():
    queue.append(raw_input(‘Enter New String: ‘).strip())

#define out queue function
def deQ():
    #judge queue whether viod
    if len(queue) == 0:
        print(‘Can not pop from an empty queue!‘)
    else:
        print(‘Removed‘ ,queue.pop(0))

#define show queue function
def viewQ():
    print(queue)

#define a dictionary to chose opration function
cmds = {‘e‘:enQ,‘d‘:deQ,‘v‘:viewQ}

#define a funtion to show menu
def showMenu():
    pr = ‘‘‘
    (E)nqueue
    (D)equeue
    (V)iew
    (Q)uit
    
    Enter choice:‘‘‘

    #double while circle make program always run
    while True:
        while True:
            try:
                #use to print menu information and get valid choice number(no space, just one bit , lower)
                choice = raw_input(pr).strip()[0].lower()
            except(EOFError,KeyboardInterrupt,IndexError):
                #if get a invalid value,return ‘q‘
                choice = ‘q‘
                
            print(‘You picked: %s ‘% choice)
            if choice not in ‘devq‘:
                print(‘Invalid option, try again!‘)
            else:
                break

        if choice == ‘q‘:
            break
        #call functions by dictionary
        cmds[choice]()

#main function
if __name__ == ‘__main__‘:
    showMenu()
    
    
 ##################################stack######################################
 #!/usr/bin/env python

‘this program use list as a stack‘

stack = []

def pushit():
    ‘input stack ‘
    stack.append(raw_input(‘Enter New Strings: ‘).strip())

def popit():
    ‘output stack‘
    if len(stack) == 0:
        print(‘Can not pop from an empty stack!‘)
    else:
        print(‘removed [‘,stack.pop(),‘]‘)

def viewStack():
    print(stack)

CMDs = {‘u‘: pushit, ‘o‘: popit, ‘v‘: viewStack}

def showMenu():
    pr = ‘‘‘
    p(U)sh
    p(O)p
    (V)iew
    (Q)uit
    Enter Choice:
 
‘‘‘
    while True:
        while True:
            try:
                choice = raw_input(pr).strip()[0].lower()
                print(choice)
            except(EOFError.KeyboardInterrupt,IndexError):
                choice = ‘q‘
            print(‘you picked: %s ‘ % choice) 
            if choice not in ‘uovq‘:
                print(‘Invalid option, try again‘)
            else:
                break

        if choice == ‘q‘:
            break
        CMDs[choice]()

if __name__ == ‘__main__‘:
    showMenu()
时间: 2024-07-31 20:34:09

python模拟队列和堆栈(列表练习)的相关文章

Java集合框架之LinkedList-----用LinkedList模拟队列和堆栈

LinkedList的特有方法: (一)添加方法 addFisrt(E e):将指定元素插入此列表的开头.//参数e可以理解成Object对象,因为列表可以接收任何类型的对象,所以e就是Object对象(传递过程即向上转型). addLast(E e):将指定元素插入此列表的结尾. JDK1.6之后: offerFirst(); offerLast();//其实前后的用法相同,换了一个名字而已. (二):获取元素方法(获取过程不删除链表元素): getFirst();返回此列表的第一个元素.如果

《模拟队列或堆栈》

1 package cn.itcast.api.b.list.subclass; 2 3 import java.util.LinkedList; 4 5 public class LinkedListTest { 6 7 public static void main(String[] args) { 8 /* 9 * 面试题:用LinkedList模拟一个堆栈或者队列数据结构. 10 * 创建一个堆栈或者队列数据结构对象.该对象中是使用LinkedList来完成的. 11 * 12 */ 1

PTA-7-22 堆栈模拟队列

本题考点:采用堆栈模拟队列 目录 解题思路 情况分析 代码实现 设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q. 所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数: int IsFull(Stack S):判断堆栈S是否已满,返回1或0: int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0: void Push(Stack S, ElementType item ):将元素item压入堆栈S: ElementType Pop(Stack S ):删除

Python学习之路15——列表实现栈和队列

栈 栈是一种后进先出(LIFO)的数据结构.你可以通过push操作来向栈中添加一个对象,也可以通过pop操作来返回并删除栈顶对象. 以下是列表模拟栈的代码: <span style="font-size:14px;">#!/usr/bin/env python 'stack.py create a stack' stack = [] def pushit(): stack.append(raw_input('Enter New string: ').strip()) def

3-08. 堆栈模拟队列(25)(ZJU_PAT 模拟)

题目链接:http://pat.zju.edu.cn/contests/ds/3-08 设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q. 所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数: (1) int IsFull(Stack S):判断堆栈S是否已满,返回1或0: (2) int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0: (3) void Push(Stack S, ElementType item ):将元素item压入堆栈S: (4)

python模拟163登陆获取邮件列表

利用cookielib和urllib2模块模拟登陆163的例子有很多,近期看了<python模拟登陆163邮箱并获取通讯录>一文,受到启发,试着对收件箱.发件箱等进行了分析,并列出了所有邮件列表及状态,包括发件人.收件人.主题.发信时间.已读未读等状态. 1.参考代码:http://hi.baidu.com/fc_lamp/blog/item/2466d1096fcc532de8248839.html%EF%BB%BF 1 #-*- coding:UTF-8 -*- 2 import urll

7-22 堆栈模拟队列

7-22 堆栈模拟队列(25 分) 设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q. 所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数: int IsFull(Stack S):判断堆栈S是否已满,返回1或0: int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0: void Push(Stack S, ElementType item ):将元素item压入堆栈S: ElementType Pop(Stack S ):删除并返回S的栈顶元素. 实现队

使用列表模拟队列操作

如下程序模拟队列先进先出(FIFO)的特性: 代码: class Queue: def __init__(self): self.__data = [] def push(self,value): self.__data.append(value) def get(self): if self.__data: return self.__data.pop(0) else: print("queue is empty") queue = Queue() queue.push(2) que

7-22 堆栈模拟队列 (25分)

没注意看题,一开始把元素类型弄成char了,搞了好久都AC不了,换成int一次就AC了. 题意: 即用两个栈来模拟队列,使两个栈协作实现队列的功能. 思路: 1.第一个栈为输入栈,第二个栈为输出栈,输入栈比输出栈要小. 2.栈满条件:输入栈满了而输出栈不为空,说明栈满了,因为输出栈还有元素的话,输入栈的元素是不能搬到输出栈的,这样会造成顺序混乱(输出栈为空时连续多次将对个输入栈栈顶元素搬到输出栈这一情况除外). 3.所以说,输入栈的元素要搬到栈顶只能在一种条件下:就是输出栈为空时,且输入栈元素必