473,808 Members | 2,797 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5431
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.tostr ing())

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(some list, tuple)
hash(tuple(some list))

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...@lexic on.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,>1 23 == 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...@skyne t.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
2086
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 implementing a very simple hash (or quasi hash) I need to be able to store a counter and a timestamp for requests from particular device MAC addresses (6 bytes, presented as xx:xx:xx:xx:xx:xx
11
3440
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 that made sense. One comment I've seen alot about is "securing the hashing routine" but no-one explains how to accomplish this. So how do I secure my hashing routine? Do I use code access security, role based security, ACLs, etc or combination?...
10
2876
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 introduce some characters in my password that are not handled properly by SQL server then. For example, password 'startreck' works just fine password 'test' does not
8
4233
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, read, write, and fd if anyone is familiar with them. Any info would be greatly helpful. Thanks, James
19
3847
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 dictionary keys, based on their content, not their identity. Is this feasible using the arrays directly, or do I need to wrap them in a struct that handles GetHashCode and Equal? If so, is such a wrapper present in the standard class library?
8
4580
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 although its unique but because it had certain characters and variable lengths I ended up using MD5 hashing of the name.
7
40830
by: dmitrey | last post by:
howto make Python list from numpy.array? Thx, D.
1
1434
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 it will be (j+1 mod n) in the insertion and searching process and in the deletion the array will rehash the rest of the elements !! actually am not so good in java and i dont even have the hashing algorithem soo if any one can help ill be more than...
1
4421
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 make program in Dynamic hashing i have to store int value in nodes user only enter int value by this value i have to find hash key and make symbol table my struct are
0
9721
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9600
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10373
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10374
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9195
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6880
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5547
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.