Find duplicate sets in list of sets

Viewed 77

I have an array of sets and I would like to check if two or more sets are the same. I don't need to look at the sets in a precise order.

example list

list = [
    {7, 12, 16, 17, 31},
    {33, 4, 8, 10, 46},
    {6, 40, 43, 22, 29},
    {2, 35, 9, 41, 31},
    {34, 38, 42, 43, 45},
    {38, 16, 20, 25, 30},
    {2, 10, 45, 19, 25},
    {4, 44, 41, 14, 16},
    {39, 40, 16, 25, 28},
    {34, 37, 45, 19, 23},
    {4, 41, 44, 14, 16},
]

within the list there are two identical sets but with number in different order. How to check for those?

2 Answers

You could use frozenset and Counter, for example, like this:

from collections import Counter

lst = [{7, 12, 16, 17, 31}, {33, 4, 8, 10, 46}, {6, 40, 43, 22, 29}, {2, 35, 9, 41, 31}, {34, 38, 42, 43, 45},
        {38, 16, 20, 25, 30}, {2, 10, 45, 19, 25}, {4, 44, 41, 14, 16}, {39, 40, 16, 25, 28}, {34, 37, 45, 19, 23},
        {4, 41, 44, 14, 16}]

counts = Counter(frozenset(s) for s in lst)

print([e for e, c in counts.items() if c > 1])

Output

[frozenset({16, 4, 41, 44, 14})]

As a side note, avoid using list as a name, it shadows the built-in list.

It doesn't matter if order is not same. You can directly compare those sets.

>>> a=[{1,2,3},{2,3,1},{4,1,3}]
>>> a[0]==a[1]
True

(I wanted to put this as comment but I can't because of low reputation.)

Edit: Other answers are more precise, but I just wanted to prove the concept

Related