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

Function find_max_recursive

maths/find_max.py:29–78  ·  view source on GitHub ↗

find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max_recursive(nums, 0, len(nums) - 1)

(nums: list[int | float], left: int, right: int)

Source from the content-addressed store, hash-verified

27
28# Divide and Conquer algorithm
29def find_max_recursive(nums: list[int | float], left: int, right: int) -> int | float:
30 """
31 find max value in list
32 :param nums: contains elements
33 :param left: index of first element
34 :param right: index of last element
35 :return: max in nums
36
37 >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
38 ... find_max_recursive(nums, 0, len(nums) - 1) == max(nums)
39 True
40 True
41 True
42 True
43 >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
44 >>> find_max_recursive(nums, 0, len(nums) - 1) == max(nums)
45 True
46 >>> find_max_recursive([], 0, 0)
47 Traceback (most recent call last):
48 ...
49 ValueError: find_max_recursive() arg is an empty sequence
50 >>> find_max_recursive(nums, 0, len(nums)) == max(nums)
51 Traceback (most recent call last):
52 ...
53 IndexError: list index out of range
54 >>> find_max_recursive(nums, -len(nums), -1) == max(nums)
55 True
56 >>> find_max_recursive(nums, -len(nums) - 1, -1) == max(nums)
57 Traceback (most recent call last):
58 ...
59 IndexError: list index out of range
60 """
61 if len(nums) == 0:
62 raise ValueError("find_max_recursive() arg is an empty sequence")
63 if (
64 left >= len(nums)
65 or left < -len(nums)
66 or right >= len(nums)
67 or right < -len(nums)
68 ):
69 raise IndexError("list index out of range")
70 if left == right:
71 return nums[left]
72 mid = (left + right) >> 1 # the middle
73 left_max = find_max_recursive(nums, left, mid) # find max in range[left, mid]
74 right_max = find_max_recursive(
75 nums, mid + 1, right
76 ) # find max in range[mid + 1, right]
77
78 return left_max if left_max >= right_max else right_max
79
80
81if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected