Search code examples
pythonpython-3.xdata-structuressetcomparison

What is the most efficient way of comparing two sets?


In Python3, What is the least time-consuming way of comparing two Sets elements(Whether they have identical elements or not)?

For example, I want a function named compareSets like below. How should I write code to make it work in the least time-consuming way?

def compareSets(a, b):
    # if (elements are identical)
    # return True

    # if (elements are not identical)
    # return False
    pass

Solution

  • To test if two sets are equal, use the equality operator (==). Here is an example from the REPL, taking advantage of iterable strings:

    >>> set('a') == set('a')
    True
    >>> set('a') == set('b')
    False
    >>> set('a') == set('ab')
    False
    >>> set('ba') == set('ab') #Shows the sets are order-independent
    True