简体   繁体   English

Python 的快速排序算法

[英]Quicksort Algorithm with Python

I study Python alone, but I don't know this problem.我一个人研究Python,但不知道这个问题。 What should I add?我应该添加什么?

condition (健康)状况

Generalize and modify the quizzical alignment code so that it can be sorted by the desired criteria.概括和修改有问题的 alignment 代码,以便可以按所需标准对其进行排序。

The method must be handled in the same way as the key parameters utilized by the sort or min or max functions in the Python 3 standard library.该方法的处理方式必须与 Python 3 标准库中的 sort 或 min 或 max 函数使用的关键参数相同。

Note that the default value of the key is lambda x:x.请注意,密钥的默认值为 lambda x:x。

def quicksort(xs, key=(lambda x: x)):
    if len(xs) > 1:
        pivot = xs[0]
        (left, right) = partition(pivot, xs[1:])
        return quicksort(left) + [pivot] + quicksort(right)
    else:
        return xs


def partition(pivot, xs, key):
    left  = [x for x in xs if x <= pivot]
    right = [x for x in xs if x >  pivot]
    return (left, right)


quicksort(['hello', 'worlds', 'hi', 'won'], len) 

If you run the code,The result of being a ['hi', 'won','hello','worlds'] should come out.如果你运行代码,应该会出现['hi', 'won','hello','worlds']结果。

See the conditions in the partition:查看分区中的条件:

x <= pivot and x > pivot x <= pivotx > pivot

Right now the operators that we're using can work on numbers, the order between numbers can be expressed with > , < and = .现在我们使用的运算符可以处理数字,数字之间的顺序可以用><=表示。

The task is to support other kinds of order, for example, we might want to be able to sort words and for that we need to be able to sort by dictionary-order or by the word's length.任务是支持其他类型的顺序,例如,我们可能希望能够对单词进行排序,为此我们需要能够按字典顺序或单词的长度进行排序。

In order to do that you'll have to implement a (lambda) function which will be passed into quicksort and which will be used for the comparison between the different items in the list.为此,您必须实现一个 (lambda) function ,它将被传递给快速排序,并将用于列表中不同项目之间的比较。

The hint that the authors gave us is that we don't have to change the operators, but rather pass in a key function that takes an item and returns a number.作者给我们的提示是,我们不必更改运算符,而是传入一个key function ,它接受一个项目并返回一个数字。 If we'll use this key function on both sides of the comparison-operator we can keep > , < and = - and still be able to compare "things" other than numbers.如果我们在比较运算符的两边都使用这个键 function 我们可以保留><= - 并且仍然能够比较数字以外的“事物”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM