bogo排序——python

版权声明:本文为博主原创文章,转载请注明此文链接,谢谢了。个人技术博客:https://wardseptember.github.io/ https://blog.csdn.net/wardseptember/article/details/81434725

from __future__ import print_function  # 在Python2环境下print必须按照python3方式书写,如print("good")
import random


def bogosort(collection):
    """
    这个我也不知道叫什么排序,暂且叫bogo排序
    默认升序
    Examples:
    >>> bogosort([0, 5, 3, 2, 2])
    [0, 2, 2, 3, 5]
    >>> bogosort([])
    []
    >>> bogosort([-2, -5, -45])
    [-45, -5, -2]
    """

    def isSorted(collection):
        if len(collection) < 2:
            return True
        for i in range(len(collection) - 1):
            if collection[i] > collection[i + 1]:
                return False
        return True

    while not isSorted(collection):   #列表不是升序序列,就进行排序
        random.shuffle(collection)   #对列表进行随机排序
    return collection

if __name__ == '__main__':
    try:
        raw_input          # Python 2
    except NameError:
        raw_input = input  # Python 3

    user_input = raw_input('输入待排序的数,用\",\"分隔:\n').strip()
    #strip() 方法用于移除字符串头尾指定的字符(默认为空格)
    unsorted = [int(item) for item in user_input.split(',')]
    print(bogosort(unsorted))

一些说明:

  • 我的github项目上有完整的算法代码,欢迎star,fork.
  • 这里的所有算法均用python实现,“翻译”自国外某程序员的项目
  • 这里的“翻译”不单单指的是英译中,而且是为每个算法添加上算法思想描述和关键代码注释。
  • 为什么要“翻译”这个项目?一方面是我想系统地学习下如何用python实现各种算法,另一方面是边学习边做笔记,通过这个项目记录自己的学习过程,再者,原项目经过“翻译”后,更容易被中国人理解,为想学习python的朋友提供一个不错的算法参考。
  • 这里的算法很多,而且有些算法比较复杂,工作量很大。如果一些朋友有空闲时间,也可以参与翻译,十分欢迎。
  • 另外我的个人博客网站也同步更新,更佳的阅读体验哦。

猜你喜欢

转载自blog.csdn.net/wardseptember/article/details/81434725
今日推荐