本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答