已处理简单场景,如何用递归实现列表连续递增数字分组?
Hey Tim, great job getting the base cases sorted out—let's nail the recursive logic for your consecutive increasing sequence problem. Here's a step-by-step breakdown with code that should solve your example scenario perfectly.
Key Recursive Idea
Instead of building the result front to back, we'll work backwards: first recursively process the rest of the list (all elements after the first), then check how the first element fits into that already-structured result. This way, we only need to compare the current element to the very first item in the recursive output—since that output is already formatted correctly.
Code Implementation
Here's a Python function that builds on your existing base cases:
def find_consecutive_increasing(lst): # Base cases you've already handled if not lst: return [] if len(lst) == 1: return [lst[0]] # Recursively process the rest of the list first rest_result = find_consecutive_increasing(lst[1:]) current = lst[0] first_item = rest_result[0] # Case 1: The first item in the recursive result is a consecutive list if isinstance(first_item, list): if first_item[0] == current + 1: # Prepend current to the existing consecutive list return [[current] + first_item] + rest_result[1:] # Case 2: The first item is a standalone number else: if first_item == current + 1: # Combine current and the number into a new consecutive list return [[current, first_item]] + rest_result[1:] # Case 3: No consecutive relation—add current as a standalone element return [current] + rest_result
How It Works for Your Example
Let's walk through [1,2,3,8,6,7] to see the recursion in action:
- We start with
current = 1and recursively process[2,3,8,6,7], which returns[[2,3],8,[6,7]]. - We check the first item of that result:
[2,3]. Since2 == 1 + 1, we prepend1to this list, giving us[[1,2,3]] + [8,[6,7]]→ your desired output[[1,2,3],8,[6,7]].
For the sub-step of processing [2,3,8,6,7]:
current = 2, recursive result from[3,8,6,7]is[3,8,[6,7]].- The first item is
3, which equals2 + 1, so we combine them into[[2,3]] + [8,[6,7]].
Test Cases to Verify
Try these to confirm it works for edge cases and other scenarios:
print(find_consecutive_increasing([1,2,3,8,6,7])) # Output: [[1,2,3],8,[6,7]] print(find_consecutive_increasing([])) # Output: [] print(find_consecutive_increasing([5])) # Output: [5] print(find_consecutive_increasing([1,3,4,6,7,8])) # Output: [1,[3,4],[6,7,8]] print(find_consecutive_increasing([9,8,7])) # Output: [9,8,7]
Why This Works
- The recursion breaks the problem into smaller subproblems (processing one less element each time) until we hit your base cases.
- By processing the rest of the list first, we ensure we only need to check the immediate next element (or the start of the next consecutive group) to decide how to integrate the current element.
- We handle both cases where the next item is a standalone number or part of an existing consecutive list.
内容的提问来源于stack exchange,提问作者Tim B

