python - How can i get union of 2D list items when there occurs any intersection (in efficient way)? -
i have 2d list in python
list = [[9, 2, 7], [9, 7], [2, 7], [1, 0], [0, 5, 4]]
i union of list items if there occurs intersection. example [9, 2, 7]
, [9, 7]
, [2, 7]
has intersection of more 1 digit. union of [9,2,7]
.
how can final list follows in efficient way ?
finallist = [[9,2,7], [0, 1, 5, 4]]
n.b. order of numbers not important.
you have graph problem. want build connected components in graph vertices elements of sublists, , 2 vertices have edge between them if they're elements of same sublist. build adjacency-list representation of input , run graph search algorithm on it, or iterate on input , build disjoint sets. here's slightly-modified connected components algorithm wrote a similar question:
import collections # build adjacency list representation of input graph = collections.defaultdict(set) l in input_list: if l: first = l[0] element in l: graph[first].add(element) graph[element].add(first) # breadth-first search graph produce output output = [] marked = set() # set of nodes connected component known node in graph: if node not in marked: # node not in seen connected component # run breadth-first search determine connected component frontier = set([node]) connected_component = [] while frontier: marked |= frontier connected_component.extend(frontier) # find unmarked nodes directly connected frontier nodes # form new frontier new_frontier = set() node in frontier: new_frontier |= graph[node] - marked frontier = new_frontier output.append(tuple(connected_component))
Comments
Post a Comment