0

I think the dict will calculate hash(key) to make sure the keys are not same, but in this case hash(v1)==hash(v2),why the dict can still find they are different.

class Vectorx:
    def __init__(self,x,y):
        self.__x=x
        self.__y=y

    @property
    def x(self):
        return self.__x

    @property
    def y(self):
        return self.__y

    def __hash__(self):
        return hash(self.x)^hash(self.y)

    def __eq__(self, other):
        return self.x==other.x and self.y== other.y
    def __str__(self):
        return 'Vectorx({x},{y})'.format(x=self.x, y=self.y)
    def __repr__(self):
        return 'Vectorx({x},{y})'.format(x=self.x, y=self.y)
v1=Vectorx(1,2)
v2=Vectorx(2,1)
print(hash(v1)==hash(v2))
print(v1==v2)
d=dict()
d[v1]='v1'
d[v2]='v2'
print(d)

True
False
{Vectorx(1,2): 'v1', Vectorx(2,1): 'v2'}
Arik
  • 53
  • 6
  • Hash tables must allow for hash collisions i.e. even if two keys have same hash value, the implementation of the table must have a strategy to insert and retrieve the key and value pairs unambiguously. – Boris Verkhovskiy Mar 11 '20 at 15:21
  • Yeah, Thanks for helping me resolve this confusion. – Arik Mar 11 '20 at 15:27

0 Answers0