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

如何用Python将N位整数拆分为M段并列出所有可能的拆分结果

N位整数拆分为M段的Python实现方案

核心逻辑很简单:长度为n的数字序列共有n-1个相邻数位的间隙,拆分为m段等价于从这n-1个间隙中选出m-1个位置插入分隔符,所有选法对应所有合法的拆分结果。

可直接运行的实现代码

我们可以用Python标准库的itertools.combinations快速实现间隙选择,不用手写多层循环,适配任意n和m的取值:

from itertools import combinations

def split_number(num: str, split_segments: int) -> list:
    num_length = len(num)
    # 输入合法性校验
    if split_segments < 1 or split_segments > num_length:
        return []
    # 所有可选间隙的索引为0到num_length-2,对应第1位后到第n-1位后
    available_gaps = range(num_length - 1)
    result = []
    # 从所有间隙中选split_segments-1个作为分隔位置
    for split_positions in combinations(available_gaps, split_segments - 1):
        parts = []
        prev_cut_pos = 0
        for pos in split_positions:
            parts.append(num[prev_cut_pos:pos+1])
            prev_cut_pos = pos + 1
        # 补充最后一段
        parts.append(num[prev_cut_pos:])
        result.append(','.join(parts))
    return result

# 测试用例:将5位数字12345拆分为3段
if __name__ == "__main__":
    split_result = split_number("12345", 3)
    for item in split_result:
        print(item)
    print(f"总拆分方式数:{len(split_result)}")

运行输出

1,2,345
1,23,45
1,234,5
12,3,45
12,34,5
123,4,5
总拆分方式数:6

输出结果完全符合组合数C(4,2)=6的预期。

无依赖回溯实现

如果你不想依赖itertools库,也可以用回溯法自己实现组合选择逻辑,效果完全一致:

def backtrack(gaps: list, select_count: int, start_idx: int, path: list, res: list):
    if len(path) == select_count:
        res.append(path.copy())
        return
    for i in range(start_idx, len(gaps)):
        path.append(gaps[i])
        backtrack(gaps, select_count, i+1, path, res)
        path.pop()

def split_number_no_lib(num: str, split_segments: int) -> list:
    num_length = len(num)
    if split_segments < 1 or split_segments > num_length:
        return []
    available_gaps = list(range(num_length - 1))
    split_positions_list = []
    backtrack(available_gaps, split_segments - 1, 0, [], split_positions_list)
    result = []
    for split_positions in split_positions_list:
        parts = []
        prev_cut_pos = 0
        for pos in split_positions:
            parts.append(num[prev_cut_pos:pos+1])
            prev_cut_pos = pos + 1
        parts.append(num[prev_cut_pos:])
        result.append(','.join(parts))
    return result

内容的提问来源于stack exchange,提问作者Siddharth Prakash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:24:03