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

如何将字符串输入转为列表形式适配现有序列检测代码?

适配列表输入的代码修改方案

针对你的需求——将原本接受字符串输入的函数,改为支持列表形式输入(如[0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0]),同时兼容现有字符串输入(如(0111100111)),需要做以下核心修改:


1. 统一输入预处理逻辑

原函数仅支持纯数字字符串,现在需要同时处理两种输入类型:

  • 若输入是列表:将每个整数元素转为字符串(方便后续统一判断连续序列)
  • 若输入是字符串:先清理掉括号、空格等非0/1字符,保留纯数字序列
# 输入预处理示例
def preprocess_input(input_data):
    if isinstance(input_data, list):
        # 列表转字符串序列,处理int元素
        return [str(num) for num in input_data]
    elif isinstance(input_data, str):
        # 清理字符串中的非0/1字符,比如括号
        cleaned = re.sub(r'[^01]', '', input_data)
        return list(cleaned)
    else:
        raise ValueError("输入必须是列表或0/1字符串")

2. 替换正则匹配为手动遍历找连续序列

原代码依赖正则表达式re.findall匹配连续字符,但正则不适用于列表输入。改为手动遍历预处理后的序列,统计连续相同元素的子串:

# 手动统计连续序列的逻辑
def get_consecutive_substrings(seq):
    if not seq:
        return []
    substrings = []
    current_char = seq[0]
    current_length = 1
    for char in seq[1:]:
        if char == current_char:
            current_length += 1
        else:
            substrings.append(current_char * current_length)
            current_char = char
            current_length = 1
    substrings.append(current_char * current_length)
    return substrings

3. 调整函数参数类型与核心逻辑

更新函数的参数类型标注,整合预处理和连续序列统计逻辑,替换原有的正则部分:


修改后的完整代码

import re
from typing import List, Union


def sequences(input_data: Union[List[int], str]):
    # 1. 输入预处理
    def preprocess(input_val):
        if isinstance(input_val, list):
            return [str(num) for num in input_val]
        elif isinstance(input_val, str):
            cleaned = re.sub(r'[^01]', '', input_val)
            return list(cleaned)
        else:
            raise ValueError("输入必须是0/1列表或包含0/1的字符串")
    
    seq = preprocess(input_data)
    if not seq:
        return ['not greater than 2']
    
    # 2. 获取所有连续子串
    def get_consecutive(seq_list):
        substrings = []
        current = seq_list[0]
        count = 1
        for c in seq_list[1:]:
            if c == current:
                count +=1
            else:
                substrings.append(current*count)
                current = c
                count =1
        substrings.append(current*count)
        return substrings
    
    substrings = get_consecutive(seq)
    
    # 3. 统计最长且长度>2的子串
    mxlength = 0
    output = ['not greater than 2']
    for substring in substrings:
        length = len(substring)
        if length > mxlength and length > 2:
            output = [substring]
            mxlength = length
        elif length == mxlength and length > 2:
            output.append(substring)
    return output


# 测试用例
print('列表输入测试:', sequences([0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0]))
print('字符串输入测试:', sequences("(0111100111)"))
print('原字符串输入测试:', sequences('0110101100'))

关键修改说明

  • 输入预处理:确保不管是列表还是带符号的字符串,都能转换成统一的字符序列,避免类型错误
  • 手动统计连续序列:摆脱对正则的依赖,同时支持列表和字符串输入的处理逻辑
  • 类型标注:使用Union[List[int], str]明确函数支持的输入类型,提升代码可读性

内容的提问来源于stack exchange,提问作者Danger Coc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:05:15