MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / kth_number

Function kth_number

divide_and_conquer/kth_order_statistic.py:26–60  ·  view source on GitHub ↗

Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43

(lst: list[int], k: int)

Source from the content-addressed store, hash-verified

24
25
26def kth_number(lst: list[int], k: int) -> int:
27 """
28 Return the kth smallest number in lst.
29 >>> kth_number([2, 1, 3, 4, 5], 3)
30 3
31 >>> kth_number([2, 1, 3, 4, 5], 1)
32 1
33 >>> kth_number([2, 1, 3, 4, 5], 5)
34 5
35 >>> kth_number([3, 2, 5, 6, 7, 8], 2)
36 3
37 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4)
38 43
39 """
40 # pick a pivot and separate into list based on pivot.
41 pivot = random_pivot(lst)
42
43 # partition based on pivot
44 # linear time
45 small = [e for e in lst if e < pivot]
46 big = [e for e in lst if e > pivot]
47
48 # if we get lucky, pivot might be the element we want.
49 # we can easily see this:
50 # small (elements smaller than k)
51 # + pivot (kth element)
52 # + big (elements larger than k)
53 if len(small) == k - 1:
54 return pivot
55 # pivot is in elements bigger than k
56 elif len(small) < k - 1:
57 return kth_number(big, k - len(small) - 1)
58 # pivot is in elements smaller than k
59 else:
60 return kth_number(small, k)
61
62
63if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

random_pivotFunction · 0.85

Tested by

no test coverage detected