我需要识别相同大小的子集对,使得它们是不相交的,并且如果我们对集合 A={a_1
这是我的代码:
n=7
cont=0
for m in range(2,n//2+1):
combs=combinations(list(range(n)),m)
combs=[set(comb) for comb in combs]
print(combs)
pairs=[(comb1,comb2) for comb1 in combs for comb2 in combs if comb1.intersection(comb2)==set()]
pairs=[pair for pair in pairs if npmin(list(pair[0]))<npmin(list(pair[1]))]
flag=True
for pair in pairs:
l1=list(pair[0])
l2=list(pair[1])
l1.sort()
l2.sort()
flag=True
for n in range(m):
flag=flag and l1[n]<l2[n]
if not flag:
cont+=1
cont
本例的预期输出,n=7,将为 70。
但是,事情是这样的,对于第二次迭代,m=3,列表梳是空的,因此对于 m=3 cont 保持相同的值,然后代码输出 35。我不明白为什么。欢迎任何帮助!
不清楚你想做什么。
但是,我做了一些更改,可能会有所帮助。
首先,您可以使用
SortedSet()
,这样您就不必每次都sort()
。
对于
m == 3
,它会打印
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 1, 5), (0, 1, 6), (0, 2, 3), (0, 2, 4), (0, 2, 5), (0, 2, 6), (0, 3, 4), (0, 3, 5), (0, 3, 6), (0, 4, 5), (0, 4, 6), (0, 5, 6), (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6) , (1,3,4),(1,3,5),(1,3,6),(1,4,5),(1,4,6),(1,5,6),(2 , 3, 4), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6), (3, 4, 5), (3,4,6),(3,5,6),(4,5,6)]
对吗?
combs
和 pairs
具有相同的变量名称。from itertools import combinations
import numpy as np
from sortedcontainers import SortedSet
def f(n):
cont = 0
for m in range(2, n // 2 + 1):
if m > n:
continue
combs = combinations(list(range(n)), m)
# if m == 3:
# print(list(combs))
# break
scombs = [set(comb) for comb in combs]
pairs = [(comb1, comb2) for comb1 in scombs for comb2 in scombs if comb1.intersection(comb2) == SortedSet()]
spairs = [pair for pair in pairs if np.min(list(pair[0])) < np.min(list(pair[1]))]
flag = True
for l1, l2 in spairs:
flag = True
l1, l2 = list(l1), list(l2)
for i in range(m):
flag = flag and l1[i] < l2[i]
if not flag:
cont += 1
return cont
print(f(7))
70