温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Python中使用pygorithm模块

发布时间:2021-03-17 16:57:40 来源:亿速云 阅读:172 作者:Leah 栏目:开发技术

如何在Python中使用pygorithm模块?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

特点

  • 易于使用

  • 容易理解的文档

  • 快速获取算法的源代码

  • 随时获取时间复杂度

安装

  • 仅需在终端中执行以下命令:

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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI