資料結構__Python實現佇列和棧
阿新 • • 發佈:2019-01-12
注:以棧為例,因為佇列只要修改popit()函式處程式碼,和修改相關提示語句即可。
#Python的棧定義與計基本操作 #佇列只是改下提示語句和popit()函式 stack=[] def pushit(): stack.append(input('輸入新的元素併入棧:').strip()) #若是佇列只要將第14行改為repr(stack.pop[0])即可 def popit(): if len(stack)==0: print('空棧!!!') else: print('退棧[',repr(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 輸入你要的操作: ''' while True: while True: try: choice=input(pr).strip()[0].lower() except (EOFError,KeyboardInterrupt,IndexError): choice='q' #若寫成中文print('\n你選擇了:[%s]' % choice)將報錯 #因為中文是Unicode而英文是ASCII,只有ASCII可以格式化輸出 print('\nYou picked:[%s]' % choice) if choice not in 'uovq': print('非法命令,重新輸入:') else: break if choice=='q': break CMDs[choice]() if __name__=='__main__': showmenu()