如何生成列表中指定长度的循环连续子序列?
Fixing the Circular Consecutive Subsequence Problem
First, let's break down why your original code isn't working as expected:
- Incorrect number of sublists: Your code uses
range(B + 1)which generates only 4 indices for B=3, but we need 5 sublists (one for each starting position in the original list of length 5). - No wrap-around handling: When slicing
A[i:i+B]near the end of the list, Python just returns whatever elements are left instead of wrapping around to the start of the list.
Correct Implementation
To solve this, we can create an extended version of the list by concatenating it with itself. This lets us easily slice the wrapped sequences as contiguous sublists. Here's the code:
def sol(A, B): list_length = len(A) # Handle edge cases (empty list or invalid subsequence length) if list_length == 0 or B <= 0 or B > list_length: return [] # Create an extended list to handle wrap-around extended_list = A + A # Generate all valid consecutive sublists of length B return [extended_list[i:i+B] for i in range(list_length)]
How It Works
- Extended List: By making
extended_list = A + A, we get[1,2,3,4,2,1,2,3,4,2]for your example. This ensures that any wrap-around sequence (like starting at index 3 or 4) is a contiguous slice in the extended list. - Iterate Over All Indices: We loop over every index in the original list (
range(list_length)), which gives us exactly the number of sublists we need. - Slice the Extended List: For each index
i,extended_list[i:i+B]will include elements from the end of the original list and start of the original list when needed.
Testing with Your Example
Calling sol([1,2,3,4,2], 3) returns:[[1, 2, 3], [2, 3, 4], [3, 4, 2], [4, 2, 1], [2, 1, 2]] — which matches your expected output perfectly.
Edge Case Handling
The code includes checks for:
- Empty input list
- Non-positive subsequence length
- Subsequence length longer than the list (adjust this if you want to allow longer sequences, but this aligns with your example's constraints)
内容的提问来源于stack exchange,提问作者abd
相关产品推荐
相关产品推荐

