You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用递归实现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]:

  1. First call: recursive_max([8,12,98]) calls recursive_max([12,98])
  2. Second call: recursive_max([12,98]) calls recursive_max([98])
  3. Third call: Hits base case (len=1) and returns 98
  4. Second call compares 12 vs 98, returns 98
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:48:21