假设一个集合[0,1,2]
我怎样才能得到所有集合的列表,如果集合在一起,它的结果是=[0,1,2]
这些子集可以是
[[0],[1],[2]]
[[0,1],[2]]
[[0],[1,2]]
[[1],[0,2]]
[[0,1,2]]
这是我试过的python代码
import collections
def get_subsets(fullset):
listrep = list(fullset)
n = len(listrep)
return [[listrep[k] for k in range(n) if i&1<<k] for i in range(2**n)]
P_Set=list(df_distance.columns)
P_Set.pop(P_Set[-1])
powerSet=get_subsets(P_Set)
powerSet=get_subsets([0,1,2,3,4])
# Finding the disjoint subset that union make fullset
def common_data(list1, list2):
result = False
# traverse in the 1st list
for x in list1:
# traverse in the 2nd list
for y in list2:
# if one common
if x == y:
result = True
return result
return result
# Delete the empty list from the power list
powerSet = [x for x in powerSet if x]
# Finding the subsets
disjointSubsetList=[]
# initialSet=P_Set
initialSet=[0,1,2,3,4]
coalitionSet=[]
for i in powerSet:
coalitionSet=[]
coalitionSet.append(i)
for j in powerSet:
if collections.Counter(i) != collections.Counter(j):
if not common_data(i,j):
coalitionSet.append(j)
if collections.Counter(list(itertools.chain.from_iterable(coalitionSet))) == collections.Counter(initialSet):
disjointSubsetList.append(coalitionSet)
coalitionSet=[]
列表[0,1,2]的结果很好,但如果其[0,1,2,3,4],则结果不正确
提前感谢您抽出时间
相关问题 更多 >
编程相关推荐