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.