Hashing in python

Martin v. Loewis martin at v.loewis.de
Sun Feb 14 04:30:36 EST 2010


> CELL_SIZE = 4
> 
> def key(point):
> 
>     return (
>         int((floor(point[0]/CELL_SIZE))*CELL_SIZE),
>         int((floor(point[1]/CELL_SIZE))*CELL_SIZE),
>         int((floor(point[2]/CELL_SIZE))*CELL_SIZE)
>     )
> 
> 
> Since python allows keys to be tuples, I think that this should work.
> Is there a better (more efficient) way to do it?

You don't say why you want to do hashing in the first place. If it is to
access elements in a lookup table, and you are now using a dictionary,
I'd suggest to replace that with a list. For 4x4x4 elements, you could
either do

table[int(point[0]/CELL_SIZE)][int(point[1]/CELL_SIZE)][int(point[2]/CELL_SIZE)]

(i.e. have nested lists), or you allocate a list of 64 elements, and use

def key(point):
  return 16*int(point[0]/CELL_SIZE) + 4*int(point[1]/CELL_SIZE) +\
            int(point[2]/CELL_SIZE)

table[key(point)]

You could even use that key function as a key to a dictionary, if you
can't use lists for some reason.

Regards,
Martin



More information about the Python-list mailing list