我正在尝试在Python中实现一个哈希函数。你认为以下函数是真正的哈希函数吗?我有10个桶和值从1到7。它还会计算碰撞次数 :)
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()
测试:
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
编辑:
我查看了所有的评论并尝试创建另一个哈希函数。这次我使用随机数来确定要进行哈希的键。这次我只有3个桶。我将尝试使用25个值,这些值介于1和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]
测试:
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]
dict
(关联映射)和set
(具有唯一性约束的集合)。 - Karl Knechtel