gpt4 book ai didi

python - 这是哈希函数吗? Python

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:24 25 4
gpt4 key购买 nike

我正在尝试在 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

编辑:

我查看了所有评论并尝试创建另一个哈希函数。这次我使用 random 来确定要散列的键。这次我只有 3 个桶。我将尝试使用 1 到 10 之间的 25 个值:

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]

最佳答案

否。哈希函数必须是确定性的。它不能依赖于随机性。

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).

来源:Hash function - Determinism (维基百科)

关于python - 这是哈希函数吗? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8344719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com