I have a list of unique tuples each containing 2 elements from 1 to 10. A total number of elements in a list is 45. I would like to divide them into 10 groups each of them containing only numbers from 1 to 10.
I have tried solve my problem using this answer:
python get groups of combinations that each member appear only once
python:
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))]
But I get repetitions, like so:
[{('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('I', 'J')},
{('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'I'), ('H', 'J')},...]
not 10 pairs , but there are 945 such pair that satisy your conditions
what i did was, get all the permutation of number, create a dictionary which
keeps all combinations as key.
now for each permutation element, I have taken them in pair of 2 ie [1,2,3,4] is [(1,2),(2,3),(3,4)]
this will create a list
now for all such list and their element, I have compared them from the dictionary whether they are present in the dictionary or not.
ps. this is a long and time-consuming solution, with graph theory we can reduce size considerably.
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)
there will be 945 such values pair that exist this way