运行代码时,请参阅下面的内容,输入是(' Zoe',14),我得到结果8,运行'查找存储桶'在线Python教程中的代码也带有(' Zoe',14),其中" def hash_string"包含,结果是2出2,当代码完成时,为什么?或者,换句话说,其他2个defs会导致该结果吗?
在'寻找桶'代码是3 def。我交换了那些def的顺序 - 结果是一样的 - 顺序真的没关系吗?
def hash_string(keyword,buckets):
out = 0
for s in keyword:
out = (out + ord(s)) % buckets
return out
Online Python Tutor "Finding Buckets":
1 def hashtable_get_bucket(table,keyword):
2 return table[hash_string(keyword,len(table))]
3
4 def hash_string(keyword,buckets):
5 out = 0
6 for s in keyword:
7 out = (out + ord(s)) % buckets
8 return out
9
10 def make_hashtable(nbuckets):
11 table = []
12 for unused in range(0,nbuckets):
13 table.append([])
14 return table
15 table = [[['Francis', 13], ['Ellis', 11]], [], [['Bill', 17],
16 ['Zoe', 14]], [['Coach', 4]], [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]]
17 print hashtable_get_bucket(table, "Zoe")
def hashtable_get_bucket(table,keyword):
return table[hash_string(keyword,len(table))]
def hash_string(keyword,buckets):
out = 0
for s in keyword:
out = (out + ord(s)) % buckets
return out
def make_hashtable(nbuckets):
table = []
for unused in range(0,nbuckets):
table.append([])
return table
这里的注释评论:
函数hashtable_get_bucket从散列返回包含给定关键字的存储桶 table,作为第一个参数传入。
如果你记得哈希表的结构,你会发现它由n个桶组成,其中一个 需要由hashtable_get_bucket函数返回。桶的索引,其中 最终将包含给定的关键字(如果关键字将出现在哈希表中), 由已定义的函数hash_string计算并返回。
函数hash_string将依次取得关键字和桶数 参数。第一个参数(关键字)很简单,因为它直接传递给了 hashtable_get_bucket函数由其调用者。第二个参数(桶数)可以 在hashmap上使用len函数计算(回想一下hashmap是如何由n个桶组成的)。
答案 0 :(得分:0)
两个函数完全相同。
但是在线部分hash_string('Zoe', 5)
被调用而不是hash_string('Zoe', 14)
5来自哪个剂量?
第2行有:
hash_string(keyword, len(table))
len(tabel)
为5
。