I making something that combination each element in list in possible way without duplicate but it took long time for working, I dont know to improve performance. I need to decrease time of my combination function and you can see in result my code not return complete answer it need to run twice for sure, Thanks.
To use: (forget about find_subsets() it work fine)
SIZE = 4
mylist = list(range(SIZE))
subsets = find_subsets(mylist)
result = combination(subsets , SIZE)
My code:
def combination(subsets, n):
subsets_size = len(subsets)
combinelist = []
templist = []
for first_element in subsets:
for follow_element in subsets:
if templist == []: # first loop
templist.append(first_element)
templist_size = len(first_element)
else:
if not isDuplicate(templist, follow_element):
templist.append(follow_element)
templist_size += len(follow_element)
# case : full element (templist has all number)
# then find combination from current again
if templist_size == n:
# add new combination to combinelist
if templist not in combinelist:
combinelist.append(templist)
# renew templist
templist = []
templist.append(first_element)
templist_size = len(first_element)
return combinelist
def isDuplicate(mainlist, subset):
for isubset in mainlist:
if len(list(set(isubset) & set(subset))) > 0:
return True
return False
Output:
Mylist
[0, 1, 2, 3]
Subsets
(0,)
(1,)
(2,)
(3,)
(0, 1)
(0, 2)
(0, 3)
(1, 2)
(1, 3)
(2, 3)
(0, 1, 2)
(0, 1, 3)
(0, 2, 3)
(1, 2, 3)
(0, 1, 2, 3)
Result
[(0, 1, 2, 3)]
[(0, 1, 2), (3,)]
[(0, 1, 3), (2,)]
[(0, 2, 3), (1,)]
[(1, 2, 3), (0,)]
[(0,), (1, 2), (3,)]
[(1,), (0, 2), (3,)]
[(2,), (0, 1), (3,)]
[(3,), (0, 1), (2,)]
[(0, 1), (3,), (2,)]
[(0, 2), (3,), (1,)]
[(0, 3), (2,), (1,)]
[(1, 2), (3,), (0,)]
[(1, 3), (2,), (0,)]
[(2, 3), (1,), (0,)]
[(0,), (1,), (2,), (3,)]
It missing [(0,1),(2,3)] [(0,2),(1,3)] [(0,3),(1,2)] and more i dont know.