gpt4 book ai didi

python - 在 python 中散列字符串会返回错误的结果?

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:55 24 4
gpt4 key购买 nike

一位导师给我布置了一项家庭作业任务,要求我创建一个对字符串进行哈希处理的过程,或者在某种意义上给出哈希表中字符串的索引(如果它经过哈希处理)。

本应返回11,却返回0,谁能帮我看看这是什么原因?

def hash_string(keyword, buckets):
ords = []
for e in string_to_list(keyword):
ords.append(ord(e))

sum_of_ords = ords.pop()

for e in ords:
sum_of_ords = sum_of_ords * e

return sum_of_ords % buckets

print(hash_string('udacity', 12)) # should return 11 but returns 0?

这是 string_to_list,我知道可能有更好的方法,但这是我知道的唯一方法,无需使用 google 搜索此类事物的内置方法

def string_to_list(str):
result_list = []
i = 0

while i < len(str):
result_list.append(str[i:i + 1])
i += 1


return result_list

我的导师是这样描述答案的,但我不明白他用 h?这只是我想要做的事情的简化版本吗?

def hash_string(keyword, buckets):
h = 0
for c in keyword:
h = (h + ord(c)) % buckets
return h

最佳答案

您似乎想在这里添加但不小心乘以了:

sum_of_ords = sum_of_ords * e

将此更改为:

sum_of_ords = sum_of_ords + e

或者,使用复合赋值:

sum_of_ords += e

附带说明一下,您可以将函数大大简化为:

def hash_string(keyword, buckets):
return sum(ord(c) for c in keyword) % buckets

关于python - 在 python 中散列字符串会返回错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55410167/

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