Open In App

Python – Paired elements grouping

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python records, we can have a problem in which we have tuple list as data and we desire to group all the elements which form a chain, i.e are indirect pairs of each other or are connected components. This kind of problem can occur in domains such as competitive programming. Let’s discuss certain way in which this task can be performed.

Input : test_list = [(1, 3), (4, 5)] Output : [] 
Input : test_list = [(1, 3), (3, 5)] Output : [{1, 3, 5}]

Method 1: Using loop + set() + intersection() 

The combination of above functionalities can be used to solve this problem. In this, we iterate for all the elements and then for all the elements occurring after that in nested loop. The intersection of elements is performed, and if, any element if found similar, i.e size >= 0, then tuple is merged in similar chain. 

Python3




# Python3 code to demonstrate working of
# Paired elements grouping
# Using loop + set() + intersection()
 
# initializing list
test_list = [(1, 3), (4, 5), (1, 7), (3, 4), (7, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Paired elements grouping
# Using loop + set() + intersection()
res = []
for sub in test_list:
    idx = test_list.index(sub)
    sub_list = test_list[idx + 1:]
    if idx <= len(test_list) - 2:
        for ele in sub_list:
            intrsct = set(sub).intersection(set(ele))
            if len(intrsct) > 0:
                res.append(set(sub + ele))
 
# printing result
print("The grouped list : " + str(res))


Output : 

The original list is : [(1, 3), (4, 5), (1, 7), (3, 4), (7, 8)]
The grouped list : [{1, 3, 7}, {1, 3, 4}, {3, 4, 5}, {8, 1, 7}]

Time Complexity: O(n*n) where n is the number of elements in the  list “test_list”. The loop + set() + intersection() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.

Method#2: Using recursion

  1. We start by creating an empty set group and an empty list result. We loop through each tuple in the sorted test_list.
  2. If group is not empty and there is an intersection between group and the set representation of the current tuple, then we update the group with the elements in the current tuple using the update() method. If group is empty or there is no intersection, then we append group to result, create a new set with the elements of the current tuple, and assign it to group. 
  3. After the loop, we append group to result if it is not empty. Finally, we return result.

Example:

Python3




def paired_elements_grouping(test_list):
   
    group = set()  # initialize an empty set
    result = []  # initialize an empty list to store results
    # sort the list of tuples to process pairs in ascending order
    for tup in sorted(test_list):
        # check if the current tuple intersects with the group
        if group and group.intersection(set(tup)):
            # if so, add the new elements to the existing group
            group.update(set(tup))
        else:
            if group:
                # if not, add the existing group to the results list
                result.append(group)
            group = set(tup)  # start a new group with the current tuple
    if group:
        result.append(group)  # add the last group to the results list
    return result
 
 
# example 1
test_list = [(1, 3), (4, 5)]
print(paired_elements_grouping(test_list))  # []
 
# example 2
test_list = [(1, 3), (3, 5)]
print(paired_elements_grouping(test_list))  # [{1, 3, 5}]


Output

[{1, 3}, {4, 5}]
[{1, 3, 5}]

Time complexity: O(n log n)
Auxiliary Space: O(n)

Method#3 : Using itertools.combinations() and a set to find common elements:

Algorithm:

  1. Import the itertools module.
  2. Define the input list of tuples test_list.
  3. Create an empty list res to store the resulting sets of grouped tuples.
  4. Iterate over all pairs of tuples from test_list using the itertools.combinations() function. The loop variable pair1 takes the first tuple of the pair, and    air2 takes the second tuple of the pair.
  5. Check if the intersection of the two tuples is non-empty using the set() and intersection() functions. If the intersection is empty, the two tuples cannot be grouped together, so continue to the next pair of tuples.
  6. f the intersection is non-empty, combine the two tuples into a single set using the set() and + operators, and append the resulting set to the res list.
  7. Continue the loop until all pairs of tuples have been considered.
  8. Print the resulting list of sets res.

Python3




import itertools
 
test_list = [(1, 3), (4, 5), (1, 7), (3, 4), (7, 8)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for pair1, pair2 in itertools.combinations(test_list, 2):
    if set(pair1).intersection(set(pair2)):
        res.append(set(pair1+pair2))
print(res)
 
# This code is contributed by Jyothi pinjala


Output

The original list is : [(1, 3), (4, 5), (1, 7), (3, 4), (7, 8)]
[{1, 3, 7}, {1, 3, 4}, {3, 4, 5}, {8, 1, 7}]

Time complexity:O(n^2) because it uses nested loops, specifically the for loop and the itertools.combinations() method which generates all possible pairs of elements in the input list.

Auxiliary space:O(n^2) because the output list res could potentially contain all pairs of the input list, which would be n^2 pairs. Additionally, the set objects created to check for intersections between pairs also contribute to the space complexity.

Method 4:  Using dictionary

Python3




# Python3 code to demonstrate working of
# Paired elements grouping
# Using dictionary
 
# initializing list
test_list = [(1, 3), (4, 5), (1, 7), (3, 4), (7, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Paired elements grouping
# Using dictionary
groups = {}
for sub in test_list:
 
    # looking for element in list
    for ele in sub:
        if ele in groups:
            groups[ele].add(sub)
        else:
            groups[ele] = {sub}
 
res = []
for group in groups.values():
 
    if len(group) > 1:
        res.append(set.union(*(set(sub) for sub in group)))
 
# printing result
print("The grouped list : " + str(res))


Output

The original list is : [(1, 3), (4, 5), (1, 7), (3, 4), (7, 8)]
The grouped list : [{1, 3, 7}, {1, 3, 4}, {3, 4, 5}, {8, 1, 7}]

Time complexity: O(n^2), where n is the length of the input list
Auxiliary space: O(n^2) 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads