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

如何生成列表中指定长度的循环连续子序列?

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

  1. 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.
  2. 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.
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:12:36