考虑使用以下类的对象创建的带有键的字典:
class Point( object ):
def __init__( self, x, y ):
self.x = x
self.y = y
def __eq__( self, other ):
return self.x == other.x
def __hash__( self ):
return self.x.__hash__()
def __ne__( self, other ):
return self.x != other.x
>>> a = Point(1,1)
>>> b = Point(0, 2)
>>> dct = {}
>>> dct[a] = 15
>>> dct[b] = 16
>>> dct[a]
15
>>> c = Point(1,None)
>>> dct[c]
15
发生这种情况是因为c
和a
共享相同的哈希并且是相等的。是否有 O(1) 方法来实现给定c
返回的函数a
(与下面的 O(n) 实现相反?):
def getKey( dct, key ):
for k in dct:
if k == key:
return k
return None