【发布时间】:2015-01-03 18:52:50
【问题描述】:
我正在阅读 pyspark here 的源代码。我对这里的便携功能感到非常困惑。
def portable_hash(x):
"""
This function returns consistant hash code for builtin types, especially
for None and tuple with None.
The algrithm is similar to that one used by CPython 2.7
>>> portable_hash(None)
0
>>> portable_hash((None, 1)) & 0xffffffff
219750521
"""
if x is None:
return 0
if isinstance(x, tuple):
h = 0x345678
for i in x:
h ^= portable_hash(i)
h *= 1000003
h &= sys.maxint
h ^= len(x)
if h == -1:
h = -2
return h
return hash(x)
我可以看到它是一个递归函数。如果输入是元组,则递归循环遍历每个元素。
以下是我的几个问题:
- 这种哈希方法是一对一映射吗?
- 这个函数只接受 None 和 tuple 和 考虑到可哈希值,我知道列表对象不是 可哈希,他们是否有意这样做。
- 我对哈希没有太多经验,这是一种非常经典的哈希方法吗?如果是,有什么资源可以让我更好地理解它吗?
【问题讨论】: