本文實例講述了Python用于學習重要算法的模塊pygorithm。分享給大家供大家參考,具體如下:
這是一個能夠隨時學習重要算法的Python模塊,純粹是為了教學使用。
特點
易于使用 容易理解的文檔 快速獲取算法的源代碼 隨時獲取時間復雜度安裝
僅需在終端中執行以下命令:pip3 install pygorithm
或者你可以在這里下載源代碼,然后通過以下命令來安裝:*如果你使用的是Python 2.7,請使用pip來安裝。如果存在用戶權限的限制,你可能需要使用
pip install --user pygorithm
這個命令來安裝。
python setup.py install
快速入門
對列表進行排序from pygorithm.sorting import bubble_sortmyList = [12, 4, 3, 5, 13, 1, 17, 19, 15]sortedList = bubble_sort.sort(myList)print(sortedList)
運行結果:
獲取當前所用函數的源代碼[1, 3, 4, 5, 12, 13, 15, 17, 19]
from pygorithm.sorting import bubble_sortcode = bubble_sort.get_code()print(code)
運行結果:
計算某個算法的時間復雜度def sort(_list):
"""
Bubble Sorting algorithm:param _list: list of values to sort
:return: sorted values
"""
for i in range(len(_list)):
for j in range(len(_list) - 1, i, -1):
if _list[j] < _list[j - 1]:
_list[j], _list[j - 1] = _list[j - 1], _list[j]
return _list
from pygorithm.sorting import bubble_sorttime_complexity = bubble_sort.time_complexities()print(time_complexity)
運行結果:
查看模塊中所有有效的函數。例如,如果你想看看排序模塊中所有的排序方法,可以執行以下命令:Best Case: O(n), Average Case: O(n ^ 2), Worst Case: O(n ^ 2).
For Improved Bubble Sort:
Best Case: O(n); Average Case: O(n * (n - 1) / 4); Worst Case: O(n ^ 2)
>>> from pygorithm.sorting import modules>>> modules()['bubble_sort', 'bucket_sort', 'counting_sort', 'heap_sort', 'insertion_sort', 'merge_sort', 'quick_sort', 'selection_sort', 'shell_sort']
測試
執行以下命令來運行所有的測試用例:
python3 -m unittest
這將運行tests/目錄下的文件中定義的所有測試用例
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
新聞熱點
疑難解答