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

Python3如何生成和为5、每位0-4的7位数字全组合?

Python生成符合条件的7位数字组合方案

要生成7位、每位数字0-4、总和为5的所有组合,itertools.combinations并不适用——它用来生成无重复元素的组合,而我们需要的是允许重复、固定长度的数字序列。下面提供两种可行方案:

方法一:直接生成+筛选(简单直观)

用itertools.product生成所有7位0-4的可能组合,再筛选出总和为5的结果。因为5^7=78125种组合,计算量很小,完全可行:

import itertools

# 生成所有7位、每位0-4的组合
all_possible = itertools.product(range(5), repeat=7)
# 筛选总和为5的有效组合
valid_combs = [list(comb) for comb in all_possible if sum(comb) == 5]

# 验证部分结果
for comb in valid_combs[:5]:
    print(comb)

方法二:基于整数拆分生成(更高效)

先把数字5拆分成7个0-4的数之和,再针对性生成所有排列,避免无效计算。拆分的所有合法情况如下:

  • 1个4 + 1个1 + 5个0
  • 1个3 + 1个2 + 5个0
  • 1个3 + 3个1 + 3个0
  • 2个2 + 1个1 + 4个0
  • 1个2 + 3个1 + 3个0
  • 5个1 + 2个0

对应代码实现:

from itertools import combinations

valid_combs = []

# 情况1:1个4 + 1个1 + 5个0
for pos4 in range(7):
    for pos1 in range(7):
        if pos4 != pos1:
            comb = [0]*7
            comb[pos4] = 4
            comb[pos1] = 1
            valid_combs.append(comb)

# 情况2:1个3 + 1个2 + 5个0
for pos3 in range(7):
    for pos2 in range(7):
        if pos3 != pos2:
            comb = [0]*7
            comb[pos3] = 3
            comb[pos2] = 2
            valid_combs.append(comb)

# 情况3:1个3 + 3个1 + 3个0
for positions in combinations(range(7), 4):
    for pos3 in positions:
        comb = [0]*7
        comb[pos3] = 3
        for pos in positions:
            if pos != pos3:
                comb[pos] = 1
        valid_combs.append(comb)

# 情况4:2个2 + 1个1 + 4个0
for positions in combinations(range(7), 3):
    for pos2s in combinations(positions, 2):
        comb = [0]*7
        for pos in pos2s:
            comb[pos] = 2
        pos1 = [p for p in positions if p not in pos2s][0]
        comb[pos1] = 1
        valid_combs.append(comb)

# 情况5:1个2 + 3个1 + 3个0
for positions in combinations(range(7), 4):
    for pos2 in positions:
        comb = [0]*7
        comb[pos2] = 2
        for pos in positions:
            if pos != pos2:
                comb[pos] = 1
        valid_combs.append(comb)

# 情况6:5个1 + 2个0
for positions in combinations(range(7), 5):
    comb = [0]*7
    for pos in positions:
        comb[pos] = 1
    valid_combs.append(comb)

# 去重并排序(可选,确保结果唯一)
unique_valid = [list(t) for t in set(tuple(c) for c in valid_combs)]
unique_valid.sort()

# 验证部分结果
for comb in unique_valid[:5]:
    print(comb)

两种方法都能生成你需要的组合,第一种适合快速实现,第二种适合对性能有要求的场景。

内容的提问来源于stack exchange,提问作者Kumaran S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:55:19