hashing an array - howto
sudhi.herle at gmail.com
sudhi.herle at gmail.com
Fri Sep 12 02:05:56 EDT 2008
On Sep 5, 9:38 am, Helmut Jarausch <jarau... at skynet.be> wrote:
> Hi,
>
> I need to hash arrays of integers (from the hash module).
>
> So, I have to derive from array and supply a __hash__ method.
I don't believe you need to derive from an array.
Here are two simple and well known hash functions you can use readily:
def djbhash(a):
"""Hash function from D J Bernstein"""
h = 5381L
for i in a:
t = (h * 33) & 0xffffffffL
h = t ^ i
return h
def fnvhash(a):
"""Fowler, Noll, Vo Hash function"""
h = 2166136261
for i in a:
t = (h * 16777619) & 0xffffffffL
h = t ^ i
return h
if __name__ == '__main__':
arr = [1001, 3001, 5001, 9001, 10011, 10013, 10015, 10017, 10019,
20011, 23001]
print djbhash(arr)
print fnvhash(arr)
And finally, here is an excellent page that explains hash functions:
http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
Here is Noll's page where he explains the FNV Hash:
http://www.isthe.com/chongo/tech/comp/fnv/
Hope this helps,
--
Sudhi
More information about the Python-list
mailing list