Python用于學習重要算法的模塊pygorithm實例淺析
本文實例講述了Python用于學習重要算法的模塊pygorithm。分享給大家供大家參考,具體如下:
這是一個能夠隨時學習重要算法的Python模塊,純粹是為了教學使用。
特點
- 易于使用
- 容易理解的文檔
- 快速獲取算法的源代碼
- 隨時獲取時間復雜度
安裝
- 僅需在終端中執(zhí)行以下命令:
pip3 install pygorithm
*如果你使用的是Python 2.7,請使用pip來安裝。如果存在用戶權(quán)限的限制,你可能需要使用
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)
運行結(jié)果:
[1, 3, 4, 5, 12, 13, 15, 17, 19]
- 獲取當前所用函數(shù)的源代碼
from pygorithm.sorting import bubble_sort code = bubble_sort.get_code() print(code)
運行結(jié)果:
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)
運行結(jié)果:
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)
- 查看模塊中所有有效的函數(shù)。例如,如果你想看看排序模塊中所有的排序方法,可以執(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相關內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
TensorFlow實現(xiàn)卷積神經(jīng)網(wǎng)絡
這篇文章主要為大家詳細介紹了TensorFlow實現(xiàn)卷積神經(jīng)網(wǎng)絡,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
Python利用yield?form實現(xiàn)異步協(xié)程爬蟲
這篇文章主要為大家詳細介紹了Python如何利用yield?form實現(xiàn)異步協(xié)程爬蟲。其實這是很古老的用法了,現(xiàn)在大多用的aiohttp庫實現(xiàn),這篇記錄僅僅用做個人的協(xié)程底層實現(xiàn)的學習,希望對大家有所幫助2022-11-11

