hash issues [WAS] Re: [Tutor] hash()ing a list

Brian van den Broek bvande at po-box.mcgill.ca
Tue Mar 29 08:38:29 CEST 2005


Danny Yoo said unto the world upon 2005-03-28 14:33:

<Snip much useful discussion>

> I know I'm rushing this, so please feel free to ask more questions about
> this.



Hi Danny, Orri, and all,

I'm really glad Orri raised the hashing issues he did, and appreciate 
your informative posts, Danny. :-)

There are some related things I've been wondering about, and, since 
hashing is under discussion, I hope no one minds if I throw my issues 
into the mix.


First issue:

*Almost* all ints are fixed points for the hashing function in the 
sense that hash(some_int) == some_int. Almost all as:

 >>> hash(-1)
-2

Any idea why -1 is the sole exception? (Perhaps alternatively: why -1 
is not a good value to use as a hash value?) I know it is the sole 
exception from having run both the following and its decrementing 
counterpart to check all the integers:

counter = 0
while True:
     if hash(counter) != counter:
         print counter, type(counter)
         break
     counter += 1

(That took a while!)


Second issue:

I must misunderstand how dictionary lookups work:

 >>> a_long = 424242424242424
 >>> long_hash = hash(a_long)
 >>> hash(long_hash) == long_hash
True
 >>> some_dict = {a_long: 4242, long_hash: 42}
 >>> some_dict[a_long]
4242
 >>> some_dict[long_hash]
42
 >>> print 'Brian is confused'
Brian is confused
 >>>

I had thought lookup was by hash value, and thus expected the access 
to some_dict to cause troubles. Yet it worked. Is it that lookup is by 
hash value, and then equality if need be so as to settle ambiguity, or 
have I completely misunderstood the mechanism of dictionary lookup?

Thanks and best to all,

Brian vdB



More information about the Tutor mailing list