python - 鉴于两个项目不能在同一个列表中,如何获得列表的所有组合?

标签 python algorithm

我目前正在尝试查找数字列表的所有可能集合,其中集合中的两个或多个元素不能在同一集合中。

例如,我有一个原始列表 [1, 2, 3, 4, 5, 6] 和一个集合列表 [{1,2}, {3,4}],这意味着 1 和 2不能在同一组 3 和 4 不能在同一组。

给定这两个输入,程序的结果应该是:

{1, 6, 3, 5}
{1, 6, 4, 5}
{2, 6, 3, 5}
{2, 6, 4, 5}

最终输出中的顺序无关紧要。

编辑:我重写了实现(这次没有递归)。现在我收到一条错误消息,提示我无法从列表中删除某些内容,因为它不存在...

def schedules(overlaps, complete):
print(complete)
final = complete.copy()
print(final)
for sch in complete:
    print(sch)
    for over in overlaps:
        if (over[0] in sch) and (over[1] in sch):
            print("This is an overlap!!!")
            final.remove(sch)
return final

这是上面代码的错误和输出:

[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 3, 6), (1, 2, 4, 5), (1, 2, 4, 
6), (1, 2, 5, 6), (1, 3, 4, 5), (1, 3, 4, 6), (1, 3, 5, 6), (1, 4, 
5, 6), (2, 3, 4, 5), (2, 3, 4, 6), (2, 3, 5, 6), (2, 4, 5, 6), (3, 
4, 5, 6)]

[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 3, 6), (1, 2, 4, 5), (1, 2, 4, 
6), (1, 2, 5, 6), (1, 3, 4, 5), (1, 3, 4, 6), (1, 3, 5, 6), (1, 4, 
5, 6), (2, 3, 4, 5), (2, 3, 4, 6), (2, 3, 5, 6), (2, 4, 5, 6), (3, 
4, 5, 6)]
(1, 2, 3, 4)
This is an overlap!!!
This is an overlap!!!
Traceback (most recent call last):
  File "schedule.py", line 24, in <module>
    result = schedules(overlaps, list(comb))
  File "schedule.py", line 19, in schedules
    final.remove(sch)
ValueError: list.remove(x): x not in list    

编辑:在 final.remove(sch) 周围添加一个 try,except block 删除了错误,但正如下面评论中所指出的,如果重叠集中有两个以上的元素,则此代码将不起作用。例如:如果重叠现在是 [{1,2}, {3,4,5}] 输出应该是:

{1,6,3}
{1,6,5}
{1,6,4}
{1,6,5}
{2,6,3}
{2,6,5}
{2,6,4}
{2,6,5}

最佳答案

建议:

  • 从重叠列表开始,每组仅使用一个元素创建所有排列。
  • 将初始列表中未出现在重叠部分的元素添加到每个结果列表中。

在 python 中,这基本上归结为 2 行,适用于任意数量的任意长度的集合:

from itertools import product

init_list =  [1, 2, 3, 4, 5, 6]
overlaps = [{1,2}, {3,4}]

# the 2 lines:
rest = tuple(el for el in init_list if not any(el in ol for ol in overlaps))
[unique + rest for unique in product(*overlaps) if all(u in init_list for u in unique)]
Out[7]: [(1, 3, 5, 6), (1, 4, 5, 6), (2, 3, 5, 6), (2, 4, 5, 6)]

关于python - 鉴于两个项目不能在同一个列表中,如何获得列表的所有组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749287/

相关文章:

Python - 检查文件名的扩展名

python - 用于 SVR 回归的 Scikit Learn 包存在问题

python - 以 "w"模式打开文件 : IOError: [Errno 2] No such file or directory

database - 部分堆排序以在 5GB 文件中找到 k 个最频繁出现的单词

c# - 高效乘法

algorithm - 如何在 O(nlogn) 中找到相交线的上包络线?

algorithm - 1 和 0 的 NxN 矩阵

python - GMM 得到不同的结果

python - 给定奇数或偶数条件,如何对列表中的偶数或奇数求和?

algorithm - 如何判断两张照片是否相同,只是存在一些亮度差异