def kth_largest(l, k):
"""
Shorthand Quicksort
Runtime: O(n * log n)
"""
# kth largest element
# is k-1th element in output
def qsort(arr, pos):
middle = len(arr)//2
pivot = arr[middle]
smaller = [i for i in arr if i < pivot]
if pos < len(smaller):
return qsort(smaller, pos)
equal = [i for i in arr if i == pivot]
if pos < len(smaller) + len(equal):
return pivot
larger = [i for i in arr if i > pivot]
return qsort(larger, pos - len(smaller) - len(equal))
return qsort(l, k-1)
The given solution in Python throws a
TypeErrorfor the given example andIndexErrorfor other examples. A couple of suggested changes:Something like this: