Python Program to find Duplicate sets in list of sets

PythonServer Side ProgrammingProgramming

When it is required to find duplicate sets in a list of sets, the ‘Counter’ and ‘frozenset’ are used.

Example

Below is a demonstration of the same

from collections import Counter

my_list = [{4, 8, 6, 1}, {6, 4, 1, 8}, {1, 2, 6, 2}, {1, 4, 2}, {7, 8, 9}]

print("The list is :")
print(my_list)
my_freq = Counter(frozenset(sub) for sub in my_list)

my_result = []
for key, value in my_freq.items():

   if value > 1 :
      my_result.append(key)

print("The result is :")
print(my_result)

Output

The list is :
[{8, 1, 4, 6}, {8, 1, 4, 6}, {1, 2, 6}, {1, 2, 4}, {8, 9, 7}]
The result is :
[frozenset({8, 1, 4, 6})]

Explanation

  • A list of set values is defined and is displayed on the console.

  • It is iterated over using the ‘frozenset’ and ‘Counter’.

  • This gives the frequency of every value in the list.

  • This is assigned to a variable.

  • An empty list is created.

  • The elements of the variable are iterated over and if the frequency is greater than 1, this is appended to the empty list.

  • This is displayed as output on the console.

raja
Published on 21-Sep-2021 07:15:03
Advertisements