Python combinations 不会按值去重:用 5 个程序看清位置、顺序与输入池

10-23 5阅读

从三条记录里挑两条,记录的显示名称恰好相同,算不算同一种组合?答案取决于业务身份。itertools 的两种组合工具按输入位置区分元素,并不替你合并相同值。把结果当成“去重后的集合”,会让计数、抽样和任务分配同时出错。

Python combinations 不会按值去重:用 5 个程序看清位置、顺序与输入池
AI 生成概念示意图:两个 A 占据不同位置,相同的 AB 值可能来自不同选择;不是软件截图。

以下五段均可独立保存运行,只使用标准库。每个 require 在失败时显式抛出异常,不依赖 assert;展示的输出已逐字比对。实测环境为 CPython 3.12.14 与 3.13.5,各运行普通模式和 -O 模式,共二十次程序执行、每套三十九项检查,不包含性能基准。

一、重复值不等于同一个位置

先把输入写成位置零、位置一、位置二,再看值。两个 A 虽然相等,仍对应两条记录;位置对零与二、一与二都会映射成 AB。官方 combinations 文档明确以位置而非值判断元素的独立性。这里所谓身份不是对象的 id,也不是按相等关系建立集合。

from itertools import combinations
from math import comb


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


values = ["A", "A", "B"]
positions = list(combinations(range(len(values)), 2))
rows = list(combinations(values, 2))
require(positions == [(0, 1), (0, 2), (1, 2)], "positions")
require(rows == [("A", "A"), ("A", "B"), ("A", "B")], "values")
require(rows == [tuple(values[i] for i in p) for p in positions], "map")
require(len(rows) == comb(3, 2) == 3, "cardinality")
require(rows.count(("A", "B")) == 2, "equal outputs")
require(len(set(rows)) == 2, "distinct value tuples")
require(all(i < j for i, j in positions), "no repeated position")
print("positions:", positions)
print("values:", rows)
print("total=3 distinct=2 checks=7")

预期输出:

positions: [(0, 1), (0, 2), (1, 2)]
values: [('A', 'A'), ('A', 'B'), ('A', 'B')]
total=3 distinct=2 checks=7

输出总数是三,按值去重后才是二。这不是工具多算,而是你换了问题。例中的 set 只用于对照这组可哈希的字符串元组,不能直接推广到含列表等不可哈希元素的结果;更不能把“先去重输入”当成无损修复,它会丢掉两个 A 同时入选的可能性。

二、顺序来自输入,不是自动按值排序

输出按位置索引的字典序推进。输入以 z 开头,第一批结果就围绕 z,而不会自动让 a 排在前面。需要按值排序时,应先确定业务排序规则再处理输入。下例还混合整数、字符串和 None:生成组合本身无需比较这些值的大小。迭代器耗尽后也不会自动从头开始。

from itertools import combinations, combinations_with_replacement


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


values = ["z", "a", "m", "b"]
expected = [("z", "a"), ("z", "m"), ("z", "b"),
            ("a", "m"), ("a", "b"), ("m", "b")]
require(list(combinations(values, 2)) == expected, "input order")
it = combinations(values, 2)
require(next(it) == ("z", "a"), "first")
require(list(it) == expected[1:], "remaining")
end = object()
require(next(it, end) is end, "exhausted")
ordered = list(combinations(sorted(values), 2))
require(ordered == [("a", "b"), ("a", "m"), ("a", "z"),
                    ("b", "m"), ("b", "z"), ("m", "z")], "sorted input")
mixed = list(combinations([1, "x", None], 2))
require(mixed == [(1, "x"), (1, None), ("x", None)], "no value sort")
repeated = list(combinations_with_replacement("ba", 2))
require(repeated == [("b", "b"), ("b", "a"), ("a", "a")], "replacement order")
print("input order:", expected)
print("mixed:", mixed)
print("replacement:", repeated)
print("checks=7")

预期输出:

input order: [('z', 'a'), ('z', 'm'), ('z', 'b'), ('a', 'm'), ('a', 'b'), ('m', 'b')]
mixed: [(1, 'x'), (1, None), ('x', None)]
replacement: [('b', 'b'), ('b', 'a'), ('a', 'a')]
checks=7

三、允许重复的是位置,仍然不会替你去重

带放回版本允许同一位置被选多次,可把位置序列理解为不下降序列;普通版本则要求严格递增。AAB 选两个时,AA 出现三次,分别来自零零、零一、一一,不能只盯着字符结果判断算法是否正确。

from collections import Counter
from itertools import combinations_with_replacement as cwr
from math import comb


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


values = ["A", "A", "B"]
positions = list(cwr(range(3), 2))
rows = list(cwr(values, 2))
require(positions == [(0, 0), (0, 1), (0, 2),
                      (1, 1), (1, 2), (2, 2)], "positions")
require(rows == [tuple(values[i] for i in p) for p in positions], "map")
require(Counter(rows) == {("A", "A"): 3, ("A", "B"): 2,
                          ("B", "B"): 1}, "multiplicity")
require(all(i <= j for i, j in positions), "nondecreasing positions")
require(len(rows) == comb(3 + 2 - 1, 2) == 6, "cardinality")
require(len(set(rows)) == 3, "distinct value tuples")
require(list(cwr("AB", 3)) == [("A", "A", "A"), ("A", "A", "B"),
                              ("A", "B", "B"), ("B", "B", "B")], "r above n")
print("positions:", positions)
print("values:", rows)
print("AA=3 AB=2 BB=1 total=6 distinct=3 checks=7")

预期输出:

positions: [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
values: [('A', 'A'), ('A', 'A'), ('A', 'B'), ('A', 'A'), ('A', 'B'), ('B', 'B')]
AA=3 AB=2 BB=1 total=6 distinct=3 checks=7

计数时令 n 为输入位置数,r 为非负整数。普通组合在 n≥r 时有 math.comb(n, r) 个;r>n 时为零。带放回组合在 n>0 时有 math.comb(n+r-1, r) 个。math.comb 文档给出二项式系数及越界约定。两条公式计算生成条数,不是按值去重后的条数。

四、空组合是一种结果,空结果却没有结果

r=0 时,两种工具都产生一次空元组,即 [()],哪怕输入为空;这与 [] 完全不同。带放回版本面对空输入和正 r 才没有结果,不能把 n=0 硬塞进含 n-1 的公式。负 r 对这两个已测版本会抛出 ValueError,而不是返回空迭代器。表驱动检查同时核对实际结果和计数。

from itertools import combinations as c, combinations_with_replacement as w
from math import comb


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


def count(make, n, r):
    if make is c:
        return comb(n, r)
    if n == 0:
        return int(r == 0)
    return comb(n + r - 1, r)


cases = [
    ("C", c, "", 0, [()]),
    ("W", w, "", 0, [()]),
    ("C", c, "A", 0, [()]),
    ("W", w, "A", 0, [()]),
    ("C", c, "A", 2, []),
    ("C", c, "", 1, []),
    ("W", w, "", 1, []),
    ("W", w, "A", 3, [("A", "A", "A")]),
]
for name, make, values, r, expected in cases:
    actual = list(make(values, r))
    require(actual == expected and len(actual) == count(make, len(values), r),
            f"{name} n={len(values)} r={r}")
    print(f"{name} n={len(values)} r={r}: {actual}")
for name, make in [("C", c), ("W", w)]:
    caught = False
    try:
        make("AB", -1)
    except ValueError:
        caught = True
    require(caught, f"{name} negative r")
    print(f"{name} r=-1: ValueError")
print("checks=10")

预期输出:

C n=0 r=0: [()]
W n=0 r=0: [()]
C n=1 r=0: [()]
W n=1 r=0: [()]
C n=1 r=2: []
C n=0 r=1: []
W n=0 r=1: []
W n=1 r=3: [('A', 'A', 'A')]
C r=-1: ValueError
W r=-1: ValueError
checks=10

五、结果逐个取,输入却已先读完

“返回迭代器”不代表输入也是按需读取。最后用只有三个元素的生成器留下读取日志:尚未调用 next,构造就已经读到 done;之后取结果不再读取原输入。此时机已对照 CPython 3.12.14 源码与 CPython 3.13.5 源码,两种构造函数都会建立输入元组池。

from itertools import combinations as c, combinations_with_replacement as w


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


for name, make, expected_first, remaining in [
    ("C", c, ("A", "B"), 2),
    ("W", w, ("A", "A"), 5),
]:
    events = []

    def source():
        for value in "ABC":
            events.append(value)
            yield value
        events.append("done")

    it = make(source(), 2)
    require(events == ["A", "B", "C", "done"], name + " eager input")
    print(name + " after construction:", events)
    first = next(it)
    require(first == expected_first, name + " first")
    rest = list(it)
    require(len(rest) == remaining, name + " remaining count")
    require(events == ["A", "B", "C", "done"], name + " no reread")
    print(f"{name} first={first} remaining={len(rest)}")
print("checks=8")

预期输出:

C after construction: ['A', 'B', 'C', 'done']
C first=('A', 'B') remaining=2
W after construction: ['A', 'B', 'C', 'done']
W first=('A', 'A') remaining=5
checks=8

因此应交给它们规模可控的有限输入。只在输出外包一层截断,并不能撤销构造时的输入读取;本文没有执行任何无限输入实验。文档中的近似生成器代码用于解释结果,不应据此推断实际调用何时开始消耗输入,也不把两个 CPython 版本的实现细节泛化到所有解释器。

落地前问清三件事:业务区分的是记录还是值,是否允许同一位置多次入选,以及输入能否完整容纳。只想知道数量时先计算,不必收集全部结果;确需枚举时保留迭代消费方式。例中的 list 用于小样本核验,不能说明大规模组合适合一次性全部保存。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。