我需要编写一个代码,该代码在列表中返回给定大小的集合的子集。 因此,首先让我们说我要从集合(0,1,2,3,4,5,6,7,8)中获得大小为3的子集
我想写出列表中的子集:
[[0,1,2],[0,2,3],[0,3,4] ....]
然后我想在其中进行递归,将除第一个元素以外的所有元素与我的dictionary(graph)进行比较,以检查我的值中是否包含列表。字典的键是我子集中的第一个元素。
例如:
在[0,1,2]中:
图[0]中的1和2是吗?
字典图就像:{0:[1,2,3,6,7],1:[0,2,4,6,7] ....}
如果我完成了所有的准备工作,就想检查下一个子集。
所以我的问题如何将其放在列表中?我知道我也有k问题,但不确定如何更改。
def indep(graph,a,b):
l=list( itertools.combinations(range(a), b))
for k in l:
k=list(k)
while j<=len(k):
for j in range(len(k)):
if k[j] in graph[k[j]]:
j+=1
else:
return "no"
答案 0 :(得分:1)
这将为您带来预期的结果
从itertools导入组合
original_set = (0,1,2,3,4,5,6,7,8)
final_set = [list(pair) for pair in combinations(l, 3)]
Out[6]:
[[0, 1, 2],
[0, 1, 3],
[0, 1, 4],
[0, 1, 5],
[0, 1, 6],
[0, 1, 7],
[0, 1, 8],
[0, 2, 3],
[0, 2, 4],
[0, 2, 5],
[0, 2, 6],
[0, 2, 7],
[0, 2, 8],
[0, 3, 4],
[0, 3, 5],
[0, 3, 6],
[0, 3, 7],
[0, 3, 8],
[0, 4, 5],
[0, 4, 6],
[0, 4, 7],
[0, 4, 8],
[0, 5, 6],
[0, 5, 7],
[0, 5, 8],
[0, 6, 7],
[0, 6, 8],
[0, 7, 8],
[1, 2, 3],
[1, 2, 4],
[1, 2, 5],
[1, 2, 6],
[1, 2, 7],
[1, 2, 8],
[1, 3, 4],
[1, 3, 5],
[1, 3, 6],
[1, 3, 7],
[1, 3, 8],
[1, 4, 5],
[1, 4, 6],
[1, 4, 7],
[1, 4, 8],
[1, 5, 6],
[1, 5, 7],
[1, 5, 8],
[1, 6, 7],
[1, 6, 8],
[1, 7, 8],
[2, 3, 4],
[2, 3, 5],
[2, 3, 6],
[2, 3, 7],
[2, 3, 8],
[2, 4, 5],
[2, 4, 6],
[2, 4, 7],
[2, 4, 8],
[2, 5, 6],
[2, 5, 7],
[2, 5, 8],
[2, 6, 7],
[2, 6, 8],
[2, 7, 8],
[3, 4, 5],
[3, 4, 6],
[3, 4, 7],
[3, 4, 8],
[3, 5, 6],
[3, 5, 7],
[3, 5, 8],
[3, 6, 7],
[3, 6, 8],
[3, 7, 8],
[4, 5, 6],
[4, 5, 7],
[4, 5, 8],
[4, 6, 7],
[4, 6, 8],
[4, 7, 8],
[5, 6, 7],
[5, 6, 8],
[5, 7, 8],
[6, 7, 8]]
答案 1 :(得分:0)
import itertools
a = [0,1,2,3,4,5,6]
# all sets here.
sets = [list(x) for x in itertools.permutations(a, 3) if x[1]==x[2]-1]
#here are all the sets
#[[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 6], [1, 2, 3], [1, 3, 4], [1, 4, 5], [1, 5, 6], [2, 0, 1], [2, 3, 4],
#[2, 4, 5], [2, 5, 6], [3, 0, 1], [3, 1, 2], [3, 4, 5], [3, 5, 6], [4, 0, 1], [4, 1, 2], [4, 2, 3], [4, 5, 6], [5, 0, 1],
#[5, 1, 2], [5, 2, 3], [5, 3, 4], [6, 0, 1], [6, 1, 2], [6, 2, 3], [6, 3, 4], [6, 4, 5]]
d = dict()
#make your thingy
for i in sets:
try:
d[i[0]] = d[i[0]]+i[1:]
except:
d[i[0]] = i[1:]
d[i[0]] = list(set(d[i[0]]))
#output D
{0: [1, 2, 3, 4, 5, 6],
1: [2, 3, 4, 5, 6],
2: [0, 1, 3, 4, 5, 6],
3: [0, 1, 2, 4, 5, 6],
4: [0, 1, 2, 3, 5, 6],
5: [0, 1, 2, 3, 4],
6: [0, 1, 2, 3, 4, 5]}
这是您想要的吗? :D