473,406 Members | 2,259 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

hashing an array - howto

Hi,

I need to hash arrays of integers (from the hash module).

So, I have to derive from array and supply a __hash__ method.
But how to hash an array (of fixed length, say 25)?
What I need is a function which maps a tuple of 25 integers
into 1 integer with good hashing properties.

Does anybody know such a thing?

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
Sep 5 '08 #1
8 5381
Helmut Jarausch wrote:
I need to hash arrays of integers (from the hash module).

So, I have to derive from array and supply a __hash__ method.
But how to hash an array (of fixed length, say 25)?
What I need is a function which maps a tuple of 25 integers
into 1 integer with good hashing properties.

Does anybody know such a thing?
Have you tried this already?

def __hash__(self):
return hash(self.tostring())

Peter
Sep 5 '08 #2
Helmut Jarausch:
I need to hash arrays of integers (from the hash module).
One of the possible solutions is to hash the equivalent tuple, but it
requires some memory (your sequence must not be tuples already):

assert not isinstance(somelist, tuple)
hash(tuple(somelist))

This is an alternative solution, it doesn't use much memory, but I am
not sure it works correctly:

from operator import xor
hash(reduce(xor, somelist))

Bye,
bearophile
Sep 5 '08 #3
On Sep 5, 11:18 am, bearophileH...@lycos.com wrote:
Helmut Jarausch:
I need to hash arrays of integers (from the hash module).

One of the possible solutions is to hash the equivalent tuple, but it
requires some memory (your sequence must not be tuples already):
why can't it be tuple already? Doesn't matter:
>>from numpy import arange
a=arange(5)
a
array([0, 1, 2, 3, 4])
>>hash(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unhashable type
>>b=tuple(a)
b
(0, 1, 2, 3, 4)
>>c=tuple(b)
c
(0, 1, 2, 3, 4)
>>hash(c)
1286958229

you can discard the tuple, so the memory requirement is transient.
Sep 5 '08 #4
Michael Palmer:
why can't it be tuple already?
Because if the input list L has tuples and lists, they end having the
same hash value:
>>L = [[1,2,3], (1,2,3)]
hash(tuple(L[0])), hash(tuple(L[1]))
(-378539185, -378539185)

But it's a not much common situation, and few hash collision pairs
can't damage much, so I agree with you that my assert was useless.
This may solve that problem anyway:

hash(type(L)) ^ hash(tuple(L))

Generally a good hashing functions uses all the input information. If
you use tuple() you ignore part of the input information, that is the
type of L. So xor-ing hash(type(L)) you use that information too.

you can discard the tuple, so the memory requirement is transient.
Right, but there's lot of GC action, it may slow down the code. So you
can start using hash(tuple(L)), but if later the code performance
comes out bad, you may try a different version that creates less
intermediate garbage.

Bye,
bearophile
Sep 5 '08 #5
John Machin:
Consider this:>>hash(123) == hash(123.0) == hash(123L)
True
Right... Can you explain me why Python designers have chosen to build
a hash() like that?

Try "uses all the information that is relevant to the task".
My knowledge of hash data structures seems not enough to understand
why.

Your alternative solution using reduce and xor may have suboptimal
characteristics ...
Right, sorry.

Bye,
bearophile
Sep 5 '08 #6
On Sep 6, 7:49*am, bearophileH...@lycos.com wrote:
John Machin:
Consider this:>>hash(123) == hash(123.0) == hash(123L)
True

Right... Can you explain me why Python designers have chosen to build
a hash() like that?
I can't channel them; my rationalisation is this:

Following the Law of Least Astonishment,
>123 == 123.0 == 123L
True

Consequently if x == y, then adict[x] and adict[y] should give the
same result.

Cheers,
John
Sep 5 '08 #7
On Sep 6, 9:30*am, John Machin <sjmac...@lexicon.netwrote:
On Sep 6, 7:49*am, bearophileH...@lycos.com wrote:
John Machin:
Consider this:>>hash(123) == hash(123.0) == hash(123L)
True
Right... Can you explain me why Python designers have chosen to build
a hash() like that?

I can't channel them; my rationalisation is this:

Following the Law of Least Astonishment,>123 == 123.0 == 123L

True

Consequently if x == y, then adict[x] and adict[y] should give the
same result.
Another reason for not folding in the type of the object is this:
>>type([])
<type 'list'>
>>hash(type([]))
505252536
>>id(type([]))
505252536

IOW hash(T) == id(T) where T is a type. id(obj) is just a memory
address which can vary between executions of the same Python binary on
the same machine ... not very reproducible. There is no guarantee in
the docs for hash about under what circumstances hash(x) != hash(x) of
course; I'm just relying on the least astonishment law again :-)

And, again, we don't know what the OP's full requirements are ...

Sep 6 '08 #8
On Sep 5, 9:38*am, Helmut Jarausch <jarau...@skynet.bewrote:
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/...t_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
Sep 12 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Matt Bull | last post by:
Hi, I apologise in advance if this is off topic, but would appreciate any pointers you chaps might be able to provide. I'm relatively novice in the art of C so am after any suggestions about...
11
by: Wm. Scott Miller | last post by:
Hello all! We are building applications here and have hashing algorithms to secure secrets (e.g passwords) by producing one way hashes. Now, I've read alot and I've followed most of the advice...
10
by: Dino M. Buljubasic | last post by:
Hi, I am using MD5 to hash my passwords and add them to database as hashed. I have noticed though that some passwords don't get recognized and I suppose that it happen because hashing might...
8
by: Foodbank | last post by:
Hi, Has anyone ever hashed a text file to disk before? I'm trying to convert an in-memory hash to disk hash and I can't find any relevant information to help me. Also, I'd like to use lseek,...
19
by: Ole Nielsby | last post by:
How does the GetHashCode() of an array object behave? Does it combine the GetHashCode() of its elements, or does it create a sync block for the object? I want to use readonly arrays as...
8
by: Maya | last post by:
Hello all, I'm using MD5 hashing in my application to give unique values to huge list of items my application receives, originally every item's name was difficult to use as an id for this item...
7
by: dmitrey | last post by:
howto make Python list from numpy.array? Thx, D.
1
by: snipes2002 | last post by:
hi all i want to make a java code to build a 16 element array and do the following things ( insert , search , delete ) using a hashing function (j mod (arraysize)) and if the index is occupied so...
1
by: Tinku | last post by:
Hi friends I know Static Hashing and i know about Dynamic Hashing, still i have problem to make program with Dynamic Hashing I am new in "C" world, please help me, my problem is: i have to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.