python模拟队列和堆栈(列表练习)
发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,##################################queue##########################################!/usr/bin/env pytho
##################################queue##########################################!/usr/bin/env python'use list as a queue'#define a void list as a void queuequeue = []#define in queue functiondef enQ(): queue.append(raw_input('Enter New String: ').strip())#define out queue functiondef 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 functiondef viewQ(): print(queue)#define a dictionary to chose opration functioncmds = {'e':enQ,'d':deQ,'v':viewQ}#define a funtion to show menudef 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 functionif __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()