python實現棧和佇列
阿新 • • 發佈:2019-01-29
利用python列表的操作,利用選單的形式實現棧和佇列
棧:
stack=[]
def push():
stack.append(input('enter: ').strip())
def pop():
if len(stack)==0:
print('connot pop from an empty stack')
else :
print('Remove[',stack.pop(),']')
def viewstack():
print(stack)
CMDS={'u':push,'o':pop,'v':viewstack}
def showmenu():
pr="""
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter chioce: """
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except(EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYour choice [%s]' % choice)
if choice not in 'uvoq':
print('Invalid option!')
else :
break
if choice=='q':
break
CMDS[choice]();
if __name__=='__main__':
showmenu()
佇列:
#queue of python
#author:gaolee
queue=[]
def push():
queue.append(input('Enter :' ).strip())
def pop():
if len(queue)==0:
print('Cannot pop from an empty queue')
else:
print('Remove [ ',queue.pop(0),' ]')
def viewQ():
print(queue)
menu={'e':push,'d':pop,'v':viewQ}
def showmenu():
pr="""
(E)nqueue
(D)equeue
(V)iewQ
(Q)uit
Enter chioce: """
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except(EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYour choice [%s]' % choice)
if choice not in 'edvq':
print('Invalid option!')
else :
break
if choice=='q':
break
menu[choice]();
if __name__=='__main__':
showmenu()