首页 / PYTHON / 这是哈希函数吗?Python
这是哈希函数吗?Python
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了这是哈希函数吗?Python,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2047字,纯文字阅读大概需要3分钟。
内容图文
![这是哈希函数吗?Python](/upload/InfoBanner/zyjiaocheng/720/41ecedb49b0e40d2a12a764bbc087680.jpg)
我试图在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所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。