码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-04-05 09:09:08      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:python   编程   语言      

栈是一种后进先出(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 popit():
	if len (stack) == 0:
		print 'Cannot pop from an empty stack!'
	else:
		print 'Remove [', repr(stack.pop()), ']'

def viewstack():
	print stack

CMDs = {'u': pushit, 'o':popit, 'v': viewstack}

def showmenu():
	pr = '''
		push<span style="white-space:pre">		</span>#u represent push
		pop<span style="white-space:pre">		</span>#o represent pop
		view<span style="white-space:pre">		</span>#v represent view
		quit<span style="white-space:pre">		</span>#q represent quit
	
		Enter choice: '''

	while True:
		while True:
			try:
				choice = raw_input(pr).strip()[0].lower()
			except (EOFError, KeyboardInterrupt, IndexError):
				choice = 'q'
	
			print '\nYou 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()
</span>

下面是运行结果:

<span style="font-size:14px;">likai@linux-ne7w:~/python> python stack.py 

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
[]

                push
                pop
                view
                quit

                Enter choice: p

You picked: [p]
Invalid option, try again

                push
                pop
                view
                quit

                Enter choice: u

You picked: [u]
Enter New string: one

                push
                pop
                view
                quit

                Enter choice: u

You picked: [u]
Enter New string: two

                push
                pop
                view
                quit

                Enter choice: u

You picked: [u]
Enter New string: three

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
['one', 'two', 'three']

                push
                pop
                view
                quit

                Enter choice: o

You picked: [o]
Remove [ 'three' ]

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
['one', 'two']

                push
                pop
                view
                quit

                Enter choice: p

You picked: [p]
Invalid option, try again

                push
                pop
                view
                quit

                Enter choice: o

You picked: [o]
Remove [ 'two' ]

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
['one']

                push
                pop
                view
                quit

                Enter choice: 
</span>


队列

队列是一种先进先出(FIFO)的数据结构

以下是列表模拟队列的代码:

<span style="font-size:14px;">#!/usr/bin/env 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 'Removed [', repr(queue.pop(0)), ']'


def viewQ():
        print queue             #calls str() internaily

CMDS = {'e': enQ, 'd': deQ, 'v': viewQ}

def showmenu():
        pr = '''</span>
            <span style="font-size:14px;">    (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 '\nYou 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()
</span>
下面是运行结果:

<span style="font-size:14px;">likai@linux-ne7w:~/python> python queue.py 

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: e

You picked: [e]
Enter New string: one

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: e

You picked: [e]
Enter New string: two

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: e

You picked: [e]
Enter New string: three

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: v

You picked: [v]
['one', 'two', 'three']

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: d

You picked: [d]
Removed [ 'one' ]

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: v

You picked: [v]
['two', 'three']

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: d

You picked: [d]
Removed [ 'two' ]

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: v

You picked: [v]
['three']

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: 
</span>




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

标签:python   编程   语言      

原文地址:http://blog.csdn.net/u012088213/article/details/44875959

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!