python堆栈与队列_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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值