Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a hash function? python

im trying to implement a hash function in python. Would you consider the following a real hash function? I've 10 buckets and values from 1 to 7. It will also count amount of collisions :)

import random

A=[1,2,3,4,5,6,7]
hashed=[]

def func():
     i=0
     count=0
     while len(A)>i:
          m=random.randint(1,10) # 10 buckets
          if m in hashed:
             count+=1
          hashed.append(m)
          print "element:",A[i], "hashed to bucket", m
          i+=1


     print "Amount of collisions:", count  


func()

Test:

element: 1 hashed to bucket 3
element: 2 hashed to bucket 2
element: 3 hashed to bucket 10
element: 4 hashed to bucket 8
element: 5 hashed to bucket 3
element: 6 hashed to bucket 10
element: 7 hashed to bucket 4
Amount of collisions: 2

EDIT:

I looked at all the comments and tried to create another hash function. This time I use random to determine the keys that are to be hashed. This time i only have 3 buckets. I will try with 25 values that are between 1 and 10:

import random


count=[]

list1 = []  # bucket 1
list2 = []  # bucket 2
list3 = []   # bucket 3

the_list = []
the_list.append(list1)
the_list.append(list2)
the_list.append(list3) # using lists within a list


def func():
   while True:
       number=random.randint(1,10)
       i=random.randint(0,len(the_list)-1)
       the_list[i].append(number)
       count.append(number)
       if len(count)>25: # testing for 25 values
           break

func()
print "Bucket 1:", the_list[0]
print "Bucket 2:", the_list[1]
print "Bucket 3:", the_list[2]

Test:

Bucket 1: [5, 9, 8, 10, 3, 10]
Bucket 2: [10, 5, 8, 5, 6, 2, 6, 1, 8]
Bucket 3: [9, 4, 7, 2, 1, 6, 7, 10, 9, 1, 5]
like image 657
John Avatar asked Aug 31 '26 10:08

John


1 Answers

No. A hash function has to be deterministic. It cannot rely on randomness.

A hash procedure must be deterministic—meaning that for a given input value it must always generate the same hash value. In other words, it must be a function of the hashed data, in the mathematical sense of the term. This requirement excludes hash functions that depend on external variable parameters, such as pseudo-random number generators or the time of day. It also excludes functions that depend on the memory address of the object being hashed, because that address may change during execution (as may happen on systems that use certain methods of garbage collection), although sometimes rehashing of the item is possible).

Source: Hash function - Determinism (Wikipedia)

like image 103
Dennis Avatar answered Sep 03 '26 05:09

Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!