【发布时间】:2022-04-09 06:15:05
【问题描述】:
这篇文章对我没有用post_link
所以我在这里问:
我有一个 python 字典:
a = {'Andres':234,'Paul':345,'Andres':675}
我有这个代码
def get_index(dict, a_string):
# Variable to store the result (updated after each iteration)
result = 0
#Variable to append the final result of each key in the dict
collisions =[]
for a_character in a_string:
# Convert the character to a number (using ord)
a_number = ord(a_character)
# Update result by adding the number
result += a_number
collisions.append(result)
# Take the remainder of the result with the size of the data list
list_index = result % len(data_list)
return collisions
返回字符串的unicode,例如:
get_index(teste, 'Andres')
returns [605]
我想要的是为每个键传递我的 dict ,值代码计算每个字符串的 de unicode_sum 并将其附加到冲突中:
我试过了:
def get_index(dict):
for k,v in teste.items:
for a_character in a_string:
# Convert the character to a number (using ord)
a_number = ord(a_character)
# Update result by adding the number
result += a_number
collisions.append(result)
我想要得到的结果是:
get_index(a)
output: [605, 402, 605]
然后我可以通过len(collision) - set(collision)来计算碰撞次数
【问题讨论】:
-
查找
collections.Counter。它可能会让你的任务变得更容易。 -
Python 不会让你拥有字典
{'Andres':234, 'Paul':345, 'Andres':675}。你实际拥有的是{'Andres':675, 'Paul':345}。 -
这也不是计算碰撞的可靠方法。序数之和为 605 的字符串不止一个。
-
如果您尝试将相同的键添加到字典中,当 Python 只是要覆盖任何现有键的值时,您为什么要“计算”冲突也不是很清楚。
-
@ddejohn 我明白你的意思。我把 Andres 放了两次只是为了得到相同的 ord() 结果!我试图让它变得简单,就像在我的哈希函数中一样(我不会使用 python dict)我会允许这种情况发生。
标签: python python-3.x