给定一个列表和排除元素,是否可以忽略包含这些元素的组合的计算?
Example 1
给定l = [1, 2, 3, 4, 5]
,我想计算size 4
的所有组合,不包括在计算之前包含(1, 3)
的组合.
结果将是:
All results: Wanted results:
[1, 2, 3, 4] [1, 2, 4, 5]
[1, 2, 3, 5] [2, 3, 4, 5]
[1, 2, 4, 5]
[1, 3, 4, 5]
[2, 3, 4, 5]
包含1 and 3个的所有组合都已删除.
Example 2
由@Eric Duminil建议
结果分别是l = [1, 2, 3, 4, 5, 6]
分、size 4
分和l = [1, 2, 3, 4, 5, 6]
分
- 不包括第二列中的
(1, 2, 3)
-
不包括第三栏中的
(1, 2)
All results: Wanted results 1 Wanted results 2 (Excluding [1, 2, 3]): (Excluding [1, 2]) [1, 2, 3, 4] [1, 2, 4, 5] [1, 3, 4, 5] [1, 2, 3, 5] [1, 2, 4, 6] [1, 3, 4, 6] [1, 2, 3, 6] [1, 2, 5, 6] [1, 3, 5, 6] [1, 2, 4, 5] [1, 3, 4, 5] [1, 4, 5, 6] [1, 2, 4, 6] [1, 3, 4, 6] [2, 3, 4, 5] [1, 2, 5, 6] [1, 3, 5, 6] [2, 3, 4, 6] [1, 3, 4, 5] [1, 4, 5, 6] [2, 3, 5, 6] [1, 3, 4, 6] [2, 3, 4, 5] [2, 4, 5, 6] [1, 3, 5, 6] [2, 3, 4, 6] [3, 4, 5, 6] [1, 4, 5, 6] [2, 3, 5, 6] [2, 3, 4, 5] [2, 4, 5, 6] [2, 3, 4, 6] [3, 4, 5, 6] [2, 3, 5, 6] [2, 4, 5, 6] [3, 4, 5, 6]
包含1 and 2 and 3个的所有组合都已从想要的结果1中删除
包含1 and 2个的所有组合都已从想要的结果2中删除
我有一个更大的组合要计算,但它需要很多时间,我想减少使用这些排除的时间.
Tried solutions
在方法1中,仍然计算组合
使用方法2,我试图修改combinations function,但在计算之前,我找不到一个适当的方法来忽略我的排除列表.
Method 1 | Method 2
|
def main(): | def combinations(iterable, r):
l = list(range(1, 6)) | pool = tuple(iterable)
comb = combinations(l, 4) | n = len(pool)
| if r > n:
for i in comb: | return
if set([1, 3]).issubset(i): | indices = list(range(r))
continue | yield tuple(pool[i] for i in indices)
else | while True:
process() | for i in reversed(range(r)):
| if indices[i] != i + n - r:
| break
| else:
| return
| indices[i] += 1
| for j in range(i+1, r):
| indices[j] = indices[j-1] + 1
| yield tuple(pool[i] for i in indices)
EDIT:
首先,感谢大家的帮助,我忘了提供更多关于约束的细节.
输出的顺序不相关,例如,如果结果为
[1, 2, 4, 5] [2, 3, 4, 5]
或[2, 3, 4, 5] [1, 2, 4, 5]
,则不重要.组合的元素应该(如果可能)排序为
[1, 2, 4, 5] [2, 3, 4, 5]
,而不是[2, 1, 5, 4] [3, 2, 4, 5]
,但这并不重要,因为组合可以在之后排序.排除列表是组合together中包含的所有项目的列表.e、 g如果我的排除列表是
(1, 2, 3)
,则不应计算包含1 and 2 and 3的所有组合.但是,允许使用1 and 2 and not 3的组合.在这种情况下,如果我排除包含(1, 2)
和(1, 2, 3)
的组合,它是完全无用的,因为所有将被(1, 2, 3)
过滤的组合都已经被(1, 2)
过滤了Multiple exclude lists必须是可能的,因为我对我的组合使用了多个约束.
Tested answers
@托比亚斯·k
@Kasramvd和@mikuszefski
谢谢