如何用递归实现Python中的数组最大值查找?
Converting Iterative Max-Finder to Recursive Approach
Hey there! Great job getting the iterative version working—let's turn that into a recursive solution. Recursion thrives on breaking big problems into smaller, identical subproblems, so here's how we can apply that to finding the maximum in an array:
Core Recursive Logic
- Base Case 1: If the array is empty, return your error message (just like your original code).
- Base Case 2: If the array has only one element, that element is the maximum—no need to recurse further.
- Recursive Step: Compare the first element of the array with the maximum value of the rest of the array. Return whichever is larger.
Updated Recursive Code
I renamed the function to recursive_max to avoid overwriting Python's built-in max() function (a common gotcha!):
def recursive_max(arr): # Handle empty array if not arr: return "List cannot be empty" # Single element is the max by default if len(arr) == 1: return arr[0] # Recursively find max of the remaining elements subarray_max = recursive_max(arr[1:]) # Return the larger of the first element and subarray max return arr[0] if arr[0] > subarray_max else subarray_max # Test with your data data = [8,2,-690,4,12,-320,0, 98] print(recursive_max(data)) # Output: 98
How It Works
Let's walk through a tiny example to see the recursion in action:
For [8, 12, 98]:
- First call:
recursive_max([8,12,98])callsrecursive_max([12,98]) - Second call:
recursive_max([12,98])callsrecursive_max([98]) - Third call: Hits base case (len=1) and returns 98
- Second call compares 12 vs 98, returns 98
- First call compares 8 vs 98, returns 98
This matches the result from your original iterative code, but uses recursion to break down the problem instead of a loop.
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

