【问题标题】:Groups of pairwise combinations where each member appears only once每个成员仅出现一次的成对组合组
【发布时间】:2019-05-28 11:04:39
【问题描述】:

我有一个唯一元组列表,每个元组包含 2 个从 1 到 10 的元素。列表中的元素总数为 45。我想将它们分成 10 个组,每个组只包含从 1 到 10 的数字。

我已尝试使用以下答案解决我的问题: python get groups of combinations that each member appear only once

蟒蛇:

from itertools import combinations, chain
l = ['A','B','C','D','E', 'F', 'G','H','I','J']
c = list(combinations(l,2))
[set(i) for i in list(combinations(c,5)) if (len(set(l) & set(chain(*i))) == len(l))]

但我得到重复,像这样:

[{('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('I', 'J')},
 {('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'I'), ('H', 'J')},...]

【问题讨论】:

  • 您能举例说明您的要求吗?还有,45个元组不能分成10个相等的组,那么怎么划分呢?
  • 当然你是对的,在这种情况下,我可以有 9 个组,每个组 5 个元素。每个元素是 2 个字母的元组,所有字母都应该是唯一的。所以从 A 到 J 的字母只出现一次。可能吗?谢谢
  • 我建议您提供所需的结果,例如['A', 'B', 'C', 'D'] 并解释为什么像上面这样的重复是不好的。
  • 一个实际的例子应该可以澄清这个问题。想象一下,我们有 10 名玩家玩一盘由 9 轮组成的国际象棋游戏。每个玩家都应该与所有其他玩家对战,但在 9 轮比赛中只能进行一次。所以在第 1 轮中,我们有 5 对:玩家 1 和 2、3 和 4、5 和 6、7 和 8、9 和 10 玩。在第 2 轮中,我们还有 5 对。它们可以是 1 和 3、2 和 4、5 和 7、6 和 9、8 和 10。

标签: python combinations itertools


【解决方案1】:

不是 10 对,但有 945 对满足您的条件

我所做的是,获取数字的所有排列,创建一个字典 将所有组合作为键。

现在对于每个排列元素,我已将它们成对 2 ie [1,2,3,4] is [(1,2),(2,3),(3,4)]

这将创建一个列表

现在对于所有此类列表及其元素,我已经从字典中比较了它们是否存在于字典中。

ps。这是一个漫长而耗时的解决方案,使用图论我们可以大大减小尺寸。

from itertools import combinations, permutations
l=['A','B','C','D','E','F','G','H','I','J']
c=list(permutations(l))
d=list(combinations(l,2))
from collections import defaultdict

dic = defaultdict(int)

for i in d:
    dic[i]=1


new =[]
for i in c:
    tmp=[]
    for j in range(1,len(i),2):
        tmp.append((i[j-1],i[j]))
    new.append(tmp)


final =[]

for i in new:
    flag =True
    count =0 
    for j in i:
        try:
            if dic[j]:
                count+=1
                pass

        except:
            flag=False
            count=0
            break
    if flag and count==5:
        final.append(i)

final2 = [tuple(sorted(i)) for i in final]   

solution = list(set(final2))
print(solution)

将有 945 个这样的值对以这种方式存在

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2021-10-30
    • 2023-03-18
    相关资源
    最近更新 更多