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

Function kth_largest_element

data_structures/arrays/kth_largest_element.py:44–111  ·  view source on GitHub ↗

Finds the kth largest element in a list. Should deliver similar results to: ```python def kth_largest_element(arr, position): return sorted(arr)[-position] ``` Args: nums: The list of numbers. k: The position of the desired kth largest element.

(arr: list[int], position: int)

Source from the content-addressed store, hash-verified

42
43
44def kth_largest_element(arr: list[int], position: int) -> int:
45 """
46 Finds the kth largest element in a list.
47 Should deliver similar results to:
48 ```python
49 def kth_largest_element(arr, position):
50 return sorted(arr)[-position]
51 ```
52
53 Args:
54 nums: The list of numbers.
55 k: The position of the desired kth largest element.
56
57 Returns:
58 int: The kth largest element.
59
60 Examples:
61 >>> kth_largest_element([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 3)
62 5
63 >>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], 1)
64 9
65 >>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], -2)
66 Traceback (most recent call last):
67 ...
68 ValueError: Invalid value of 'position'
69 >>> kth_largest_element([9, 1, 3, 6, 7, 9, 8, 4, 2, 4, 9], 110)
70 Traceback (most recent call last):
71 ...
72 ValueError: Invalid value of 'position'
73 >>> kth_largest_element([1, 2, 4, 3, 5, 9, 7, 6, 5, 9, 3], 0)
74 Traceback (most recent call last):
75 ...
76 ValueError: Invalid value of 'position'
77 >>> kth_largest_element(['apple', 'cherry', 'date', 'banana'], 2)
78 'cherry'
79 >>> kth_largest_element([3.1, 1.2, 5.6, 4.7,7.9,5,0], 2)
80 5.6
81 >>> kth_largest_element([-2, -5, -4, -1], 1)
82 -1
83 >>> kth_largest_element([], 1)
84 -1
85 >>> kth_largest_element([3.1, 1.2, 5.6, 4.7, 7.9, 5, 0], 1.5)
86 Traceback (most recent call last):
87 ...
88 ValueError: The position should be an integer
89 >>> kth_largest_element((4, 6, 1, 2), 4)
90 Traceback (most recent call last):
91 ...
92 TypeError: 'tuple' object does not support item assignment
93 """
94 if not arr:
95 return -1
96 if not isinstance(position, int):
97 raise ValueError("The position should be an integer")
98 if not 1 <= position <= len(arr):
99 raise ValueError("Invalid value of 'position'")
100 low, high = 0, len(arr) - 1
101 while low <= high:

Callers

nothing calls this directly

Calls 1

partitionFunction · 0.70

Tested by

no test coverage detected