LFJ LFJ - 3 months ago 12
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)
14
>>> my_simple_hash(1,4,3)
15
>>> my_simple_hash(4,3,1)
23


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:

1,3,4
1,4,3
3,1,4
3,4,1
4,1,3
4,3,1


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

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

Answer

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