假設我們有一個包含 N 個串列的串列。例如:
L = [['A','B','C','D','E'], ['A','B','C'],['B','C','D'],['C','D'],['A','C','D']]
我想找到此串列中出現的最長公共子集以及相應的計數。在這種情況下:
ans = {'A,B,C':2, 'A,C,D':2, 'B,C,D':2}
我認為這個問題與我的類似,但我很難理解 C# 代碼。
uj5u.com熱心網友回復:
我假設“公共子集”是一個集合,它是陣列中至少兩個串列的子集。
考慮到這一點,這里有一個解決方案。
from itertools import combinations
from collections import Counter
L = [['A','B','C','D','E'], ['A','B','C'],['B','C','D'],['C','D'],['A','C','D']]
L = [*map(frozenset,L)]
sets = [l1&l2 for l1,l2 in combinations(L,2)]
maxlen = max(len(s) for s in sets)
sets = [s for s in sets if len(s) == maxlen]
count = Counter(s for s in sets for l in L if s <= l)
dic = {','.join(s):k for s,k in count.items()}
結果字典dic:
{'A,B,C': 2, 'B,C,D': 2, 'A,C,D': 2}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427015.html
上一篇:查找多邊形的層次結構
