Python算法模块pygorithm Python用于学习重要算法的模块pygorithm实例浅析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python算法模块pygorithm Python用于学习重要算法的模块pygorithm实例浅析

DemonHunter211   2021-03-30 我要评论

本文实例讲述了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程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们