0

I study Python alone, but I don't know this problem. What should I add?

condition

Generalize and modify the quizzical alignment code so that it can be sorted by the desired criteria.

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.

Note that the default value of the key is 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.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
JFLA
  • 1
  • 1

1 Answers1

0

See the conditions in the partition:

x <= pivot and x > 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.

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. 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.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • @N.Wouda thanks for your feedback, maybe the description was not clear enough, I added another paragraph - hope it clarifies it. – Nir Alfasi Jun 03 '21 at 10:41