0

I come from C++ and am new to Python. I have a class as follows.

 class pair:
    u=0
    v=0
    def __init__(self, x,y):
        self.u=x
        self.v=y


    def __eq__(self,ot):
        if self.u==ot.u and self.v==ot.v:
            return True

        return False        

I want a function that returns the intersection of two lists of pairs.

def intersection(P,Q):
     return len(set(P).intersection(set(Q)))

and I get this error:

TypeError: unhashable type: 'pair'

Coming from C++ I don't understand why it is not allowed to turn a list like this to a set. Can one take an immutable snapshot of the list to make the set?

Reza
  • 388
  • 2
  • 14
  • 2
    Also, you don't need to define class attributes `u` and `v`, they get overridden anyways. – internet_user Jan 17 '18 at 19:24
  • 1
    You can create a [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple), which will implement hashing and equality for you and be immutable (like a tuple… but with named fields). `pair = namedtuple('pair', ['u', 'v'])` – Ry- Jan 17 '18 at 19:26
  • Sets require hashable elements. This is what gives `in` fast lookup performance within sets and keys of dicts. A simple solution is to use tuples instead of lists. You can also implement your own `__hash__` method if you'd like. – pylang Jan 17 '18 at 19:33
  • I defined __hash__ and __key methods using this post: https://stackoverflow.com/questions/2909106/whats-a-correct-and-good-way-to-implement-hash and now my function works. – Reza Jan 17 '18 at 19:39

0 Answers0