假設我在圖中有 5 個點,v = [0,1,2,3,4]。
包含所有可能組合的串列如下所示:
[(), (0,), (1,), (2,), (3,), (4,), (0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4),
(2, 3), (2, 4), (3, 4), (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4),
(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (0, 1, 2, 3), (0, 1, 2, 4), (0, 1, 3, 4),
(0, 2, 3, 4), (1, 2, 3, 4), (0, 1, 2, 3, 4)]
現在假設我有以下優勢:
[(0, 3), (1, 2), (2, 3), (2, 4), (3, 4)]
讓我們以 (0,3) 為例。如您所見,這是圖中的一條邊,因此應丟棄所有包含 0 和 3 的組合,例如 (0,3)、(0,1,3) 等。
如何制作使用條件來驗證可能組合是否為 2 個相鄰頂點的代碼?
生成可能組合的代碼如下:
list_combinations = list()
for n in range(len(N_vert) 1):
list_combinations = list(combinations(vert, n))
n_comb = len(list_combinations)
uj5u.com熱心網友回復:
您可以檢查,對于每個組合,一個邊是它的子集
vert = [0, 1, 2, 3, 4]
edges = [(0, 3), (1, 2), (2, 3), (2, 4), (3, 4)]
edges = [set(edge) for edge in edges]
list_combinations = []
for n in range(len(vert) 1): # start loop at 1 to remove the empty tuple
for comb in combinations(vert, n):
if not any(edge.issubset(comb) for edge in edges):
list_combinations.append(comb)
print(list_combinations)
# [(), (0,), (1,), (2,), (3,), (4,), (0, 1), (0, 2), (0, 4), (1, 3), (1, 4), (0, 1, 4)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515903.html
標籤:Python列表组合
