Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions.
Below are some ways to achieve this.]
Sure! Here's a Python program that merges a list of lists by combining sublists that share at least one common element:
def merge_lists(lst): merged = [] while lst: sublist = lst.pop(0) i = 0 while i < len(merged): if set(sublist) & set(merged[i]): sublist = list(set(sublist) | set(merged.pop(i))) else: i += 1 merged.append(sublist) return merged
This function takes in a list of lists as its argument, and returns a new list where any sublists that share at least one element have been combined. It does this by iteratively popping sublists from the input list, and checking if they have any elements in common with any of the sublists already in the merged
list. If a common element is found, the two sublists are merged together by taking the set union of their elements. If no common element is found, the current sublist is simply appended to the merged
list.
Here's an example usage of this function:
>>> lst = [[1, 2], [2, 3], [4, 5], [6, 7], [7, 8, 9]] >>> merge_lists(lst) [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
In this example, the sublists [1, 2]
and [2, 3]
share the common element 2
, so they are merged together into [1, 2, 3]
. Similarly, the sublists [6, 7]
and [7, 8, 9]
share the common element 7
, so they are merged together into [6, 7, 8, 9]
. The resulting merged list has three sublists with no common elements between them.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.