本文实例讲述了Python用于学习重要算法的模块pygorithm。分享给大家供大家参考,具体如下:
这是一个能够随时学习重要算法的Python模块,纯粹是为了教学使用。
特点
- 易于使用
- 容易理解的文档
- 快速获取算法的源代码
- 随时获取时间复杂度
安装
- 仅需在终端中执行以下命令:
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)
- 查看模块中所有有效的函数。例如,如果你想看看排序模块中所有的排序方法,可以执行以下命令:
> 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入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
更新日志
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】