2 回答

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
我認(rèn)為你看待這個(gè)問(wèn)題的方式是錯(cuò)誤的。我認(rèn)為最好刪除包含無(wú)法使用的元素的任何集合(即{4,5}
在查找時(shí)刪除集合{1,2,3,4}
。然后創(chuàng)建union
所有其他集合并查看這是否等于您的輸入集合。
這樣,您將不需要找到所有組合,只需首先執(zhí)行(最多)O(n*len(sets)) 消除步驟。
graphs = [i for i in graphs if i.issubset(input1) ]
檢查答案:
result = set().union(*graphs) == input1

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
您可以找到 的所有組合itertools.combinations,然后簡(jiǎn)單地比較這些組合:
from itertools import combinations, chain
def check(graphs, inp):
for i in range(1, len(graphs)+1):
for p in combinations(graphs, i):
if set(chain(*p)) == inp:
return True
return False
graphs = [{1, 2, 3}, {4, 5}, {6}]
input1 = {1, 2, 3, 6}
input2 = {1, 2, 3, 4}
print(check(graphs, input1))
print(check(graphs, input2))
印刷:
True
False
添加回答
舉報(bào)