圖片來自 unsplash
數據結構,我們對它已經是耳熟能詳。對于計算機相關專業的大學生來說,它是一門專業必修課。從事軟件開發的人員則把它作為謀生必備技能。這充分體現數據結構的重要性。因此,我們對數據結構是不得不學。
雖然數據結構的實現不限制語言,但市面上很多教程書籍都是以 C 語言作為編程語言進行講解。如果你喜歡且在學習 Python,可能會陷入苦于這樣的煩惱中。那就是沒有 Python 版本的數據結構實現代碼。莫慌!我給大家推薦一個第三方庫,它能讓你這種煩惱立刻云消霧散。
它就是Pygorithm
Pygorithm 是由一個熱心腸的印度小哥編寫的開源項目。他編寫創建該庫的初衷是處于教學目的。我們不僅可以閱讀源碼的方式學習數據結構,而且可以把它當做現成工具來使用。
安裝
安裝 python 庫,我推薦使用 pip 方式,方便又省事。
pip install Pygorithm
# 如果出現因下載失敗導致安裝不上的情況,可以先啟動 ss 再執行安裝命令
# 或者在終端中使用代理
pip --proxy http://代理ip:端口 install Pygorithm
支持的類型
Pygorithm 實現的數據結構類型有以下這幾種,括號中表示包名。
-
棧
- 棧 (data_structures.stack.Stack)
- 中綴表達式轉換為后綴表達式 (data_structures.stack.InfixToPostfix)
-
隊列
- 隊列 (data_structures.queue.Queue)
- 雙端隊列 (data_structures.queue.Deque)
-
鏈表
- 單向鏈表 (data_structures.linked_list.SinglyLinkedList)
- 雙向鏈表 (data_structures.linked_list.DoublyLinkedList)
-
樹
- 二叉樹 (data_structures.tree.BinaryTree)
- 搜索二叉樹 (data_structures.tree.BinarySearchTree)
-
圖
- 圖 (data_structures.graph.Graph)
- 拓撲排序 (data_structures.graph.TopologicalSort)
- 有向圖 (data_structures.graph.CheckCycleDirectedGraph)
- 無向圖 (data_structures.graph.CheckCycleUndirectedGraph)
-
堆
- 堆 (data_structures.heap.Heap)
-
字典樹
- 字典樹 (data_structures.trie.Trie)
常見算法
你也許沒有想到吧。Pygorithm 中也實現一些常見的路徑搜索、查找、排序等算法。
常見的路徑搜索算法:
- Dijkstra(迪杰斯特拉)
- Unidirectional AStar(單向 A*算法)
- BiDirectional AStar(雙向 A*算法)
常見的查找算法:
- Linear Search (線性查找)
- Binary Search (二分法查找)
- Breadth First Search (廣度優先搜索)
- Depth First Search (深度優先搜索)
常見的排序算法:
- bubble_sort(冒泡算法)
- bucket_sort(桶排序)
- counting_sort (計數排序)
- heap_sort(堆排序)
- insertion_sort(插入排序)
- merge_sort(歸并排序)
- quick_sort (快速排序)
- selection_sort(選擇排序)
- shell_sort(希爾排序)