Python 資料結構之堆棧執行個體代碼,python堆棧
Python 堆棧
堆棧是一個後進先出(LIFO)的資料結構. 堆棧這個資料結構可以用於處理大部分具有後進先出的特性的程式流 .
在堆棧中, push 和 pop 是常用術語:
- push: 意思是把一個對象入棧.
- pop: 意思是把一個對象出棧.
下面是一個由 Python 實現的簡單的堆棧結構:
stack = [] # 初始化一個列表資料類型對象, 作為一個棧def pushit(): # 定義一個入棧方法 stack.append(raw_input('Enter New String: ').strip()) # 提示輸入一個入棧的 String 對象, 調用 Str.strip() 保證輸入的 String 值不包含多餘的空格def popit(): # 定義一個出棧方法 if len(stack) == 0: print "Cannot pop from an empty stack!" else: print 'Remove [', `stack.pop()`, ']' # 使用反單引號(` `)來代替 repr(), 把 String 的值用引號擴起來, 而不僅顯示 String 的值def viewstack(): # 定義一個顯示堆棧中的內容的方法 print stackCMDs = {'u':pushit, 'o':popit, 'v':viewstack}# 定義一個 Dict 類型對象, 將字元對應表到相應的 function .可以通過輸入字元來執行相應的操作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() # Str.strip() 去除 String 對象前後的多餘空格 # Str.lower() 將多有輸入轉化為小寫, 便於後期的統一判斷 # 輸入 ^D(EOF, 產生一個 EOFError 異常) # 輸入 ^C(中斷退出, 產生一個 keyboardInterrupt 異常) 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]() # 擷取 Dict 中字元對應的 functionName, 實現函數調用if __name__ == '__main__': showmenu()
NOTE: 在堆棧資料結構中, 主要應用了 List 資料類型對象的 容器 和 可變 等特性, 表現在 List.append() 和 List.pop() 這兩個清單類型內建函數的調用.
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!