Python用于學習重要算法的模塊pygorithm實例淺析
本文實例講述了Python用于學習重要算法的模塊pygorithm。分享給大家供大家參考,具體如下:
這是一個能夠隨時學習重要算法的Python模塊,純粹是為了教學使用。
特點
- 易于使用
- 容易理解的文檔
- 快速獲取算法的源代碼
- 隨時獲取時間復雜度
安裝
- 僅需在終端中執(zhí)行以下命令:
pip3 install pygorithm
*如果你使用的是Python 2.7,請使用pip來安裝。如果存在用戶權限的限制,你可能需要使用
pip install --user pygorithm
這個命令來安裝。
- 或者你可以在這里下載源代碼,然后通過以下命令來安裝:
python setup.py install
快速入門
- 對列表進行排序
from pygorithm.sorting import bubble_sort myList = [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_sort code = 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_sort time_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)
- 查看模塊中所有有效的函數。例如,如果你想看看排序模塊中所有的排序方法,可以執(zhí)行以下命令:
>>> from pygorithm.sorting import modules >>> modules() ['bubble_sort', 'bucket_sort', 'counting_sort', 'heap_sort', 'insertion_sort', 'merge_sort', 'quick_sort', 'selection_sort', 'shell_sort']
測試
執(zhí)行以下命令來運行所有的測試用例:
python3 -m unittest
這將運行tests/目錄下的文件中定義的所有測試用例
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
windows10下安裝TensorFlow Object Detection API的步驟
這篇文章主要介紹了windows10下安裝TensorFlow Object Detection API的步驟,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06一文搞懂Python的hasattr()、getattr()、setattr()?函數用法
python中的getattr()、setattr()、hasattr()函數均是對類屬性或方法的操作,其中getattr()用于獲取類或實例中指定方法獲取屬性的值,setattr()用于設置類或實例中屬性或方法,hasattr()用于判斷類或實例中是否存在指定的屬性或方法,本文通過例子給大家詳解,一起看看吧2022-04-04Python字符串和正則表達式中的反斜杠(''\'')問題詳解
在本篇文章里小編給大家整理的是關于Python字符串和正則表達式中的反斜杠('\')問題以及相關知識點,有需要的朋友們可以學習下。2019-09-09python機器學習混淆矩陣及confusion?matrix函數使用
這篇文章主要為大家介紹了python機器學習混淆矩陣confusion_matrix函數使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06