【发布时间】:2019-04-17 22:26:01
【问题描述】:
对于一般的哈希表实现:
计算密钥的哈希值,
hash(key)=hashcode将哈希码映射到表/数组。
hashcode % array_length = index一旦我们得到索引,我们就在该索引处的链表中添加一个节点(键、值、更新下一个指针)。
那么,问题是,两者有什么区别:
def _get_index(self, key):
# compute the hashcode
hash_code = hash(key)
array_index = hash_code & 15 # FIXME : why?
return array_index
和
array_index = hash_code % 15
例如: 输入:
hm =MyHashMap()
hm.put("1", "sachin")
hm.put("2", "sehwag")
hm.put("3", "ganguly")
print(hm.get("1"))
print(hm.get("2"))
print(hm.get("3"))
输出:
sachin
sehwag
ganguly
'&' 运算符而不是 '%' 这对我来说没有意义吗?因为它在计算索引时并不总是作为 % 运算符工作,但是,我见过开发人员在 Hashtable 的某些实现中使用 &
有什么建议吗?
【问题讨论】:
标签: python python-3.x hash hashmap hashcode