LFJ LFJ - 1 year ago 113
Python Question

python lib for custom hash function

I need a hash function to take a sequence of decimal numbers and return a decimal number as hash value.

for example:

>> def my_simple_hash(*args):
return reduce(lambda x1, x2: 2*x1 + x2, args)

>>> my_simple_hash(1,3,4)
>>> my_simple_hash(1,4,3)
>>> my_simple_hash(4,3,1)

My questions are:

  1. does python has a built-in lib to do this more efficiently?

  2. how could I make the output hash value in a relative small range?

Question 2 explanation:

because 1, 3, 4 has six different combinations as following:


the corresponding output is
[14, 15, 18, 21, 21, 23]
, and I expect the hash values of the
output would be something like
(a small range)

any suggestions would be appreciated.
thanks in advance :-)

Answer Source

If you just want to hash a number sequence you can do

def my_hash(*args):
    return hash(args)

which returns the hash (for the current run of the program) of the args-tuple (hash is fast and well tested for builtin-types) - but this is still most often a large number.

For getting a smaller value you can take the modulo like

def my_hash(*args):
    return hash(args)%10 # or whatever number you like

Actually you could also use

def my_hash(*args):
    return sum(args)%10 # or whatever number you like

which doesnt change between runs of the program but sum does not distribute the results evenly at all.

Warning: These are not cryptographical hashes