【发布时间】:2015-07-07 22:55:30
【问题描述】:
我不确定我正在尝试编写的代码的适当数学术语。我想生成唯一整数的组合,其中每个组合的“有序子集”用于排除某些后来的组合。
希望一个例子能说明这一点:
from itertools import chain, combinations
mylist = range(4)
max_depth = 3
rev = chain.from_iterable(combinations(mylist, i) for i in xrange(max_depth, 0, -1))
for el in list(rev):
print el
该代码生成的输出包含我想要的所有子集,但也包含一些我不想要的额外子集。我已经手动插入了 cmets 来指示我不想要哪些元素。
(0, 1, 2)
(0, 1, 3)
(0, 2, 3)
(1, 2, 3)
(0, 1) # Exclude: (0, 1, _) occurs as part of (0, 1, 2) above
(0, 2) # Exclude: (0, 2, _) occurs above
(0, 3) # Keep
(1, 2) # Exclude: (1, 2, _) occurs above
(1, 3) # Keep: (_, 1, 3) occurs above, but (1, 3, _) does not
(2, 3) # Keep
(0,) # Exclude: (0, _, _) occurs above
(1,) # Exclude: (1, _, _) occurs above
(2,) # Exclude: (2, _) occurs above
(3,) # Keep
因此,我的生成器或迭代器的期望输出将是:
(0, 1, 2)
(0, 1, 3)
(0, 2, 3)
(1, 2, 3)
(0, 3)
(1, 3)
(2, 3)
(3,)
我知道我可以列出所有(想要的和不需要的)组合,然后过滤掉我不想要的组合,但我想知道是否有更高效的基于生成器或迭代器的方式。
【问题讨论】:
-
您可以将所有子集散列到字典中。所以如果你生成 (0, 1, 2) 写一个方法来散列 {(0,): True, (1,): True, (0, 1): True, (0, 2): True, (0, 1, 2): 真 } 等等。然后你可以在这个哈希表中查找,看看你是否想要新的集合。
标签: python iterator generator combinations itertools