python - 对字典中的项目进行二进制搜索
问题描述
嗨,我有一个问题需要解决
要求是我必须使用它Binary Search Algorithm
来执行此操作。
我有一本这样的字典:
inven = {1 : ["Lettuce", "Fresh Cut Lettuce", 1.30, 1000, False],
2 : ["Apple", "Red big and round", 1.20, 1000, False],
3 : ["Orange", "Orange big and round", 1.10, 1000, False],
4 : ["Peach", "Pink big and round", 1.50, 1000, False],
5 : ["Pear", "Green big and semi round", 1.30, 1000, False],
6 : ["Plum", "Red small and round", 0.60, 1000, False]}
所以这个字典的键是1,2,3,4,5,6
,值是键所属的列表。
我想使用Binary Search Algorithm
来查找key
值"Orange"
所属的。
我这可能吗?另外,如果不可能,请指导我找到Algorithm
可以为我解决这个问题的人。请我知道我可以运行一个for
循环并解决这个问题,但这是我使用算法的要求。
解决方案
使用这些键,您不能使用二进制搜索,但如果您使用正确的排序键,您将能够根据需要应用任何搜索算法。
您可以通过计算每个单词的值来获取真正的键,在 Python 中,有一个函数调用ord
,可以根据 ASCII/UNICODE 表将字符转换为 int 值。因此,您可以使用如下函数计算密钥:
def key_calculator(word: str) -> int:
"""
This function converts any string to integer key.
pseudocode:
key_value = 0
for each character in the string:
key_value += (character index) + (character value)
"""
# init key_value
key_value = 0
# itarate in word length range
for i in range(len(word)):
# add the character index with the character value.
# convert the letter to lower to avoid case sensitivity.
key_value += i + ord(word[i].lower())
# return the key
return key_value
现在您可以使用以下函数计算每个单词键:
inven = {key_calculator(value[0]): value for _, value in inven.items()}
这将给我们这个 dict 结果:
inven = {
779: ["Lettuce", "Fresh Cut Lettuce", 1.3, 1000, False],
540: ["Apple", "Red big and round", 1.2, 1000, False],
651: ["Orange", "Orange big and round", 1.1, 1000, False],
523: ["Peach", "Pink big and round", 1.5, 1000, False],
430: ["Pear", "Green big and semi round", 1.3, 1000, False],
452: ["Plum", "Red small and round", 0.6, 1000, False],
}
最后一步是根据键对字典进行排序:
# sort inven dict keys
sorted_keys = sorted(inven.keys())
# sort inven dict based on sorted_keys
inven = {key: inven[key] for key in sorted_keys}
这将为我们提供排序的 dict 结果:
inven = {
430: ["Pear", "Green big and semi round", 1.3, 1000, False],
452: ["Plum", "Red small and round", 0.6, 1000, False],
523: ["Peach", "Pink big and round", 1.5, 1000, False],
540: ["Apple", "Red big and round", 1.2, 1000, False],
651: ["Orange", "Orange big and round", 1.1, 1000, False],
779: ["Lettuce", "Fresh Cut Lettuce", 1.3, 1000, False],
}
现在您可以使用任何搜索算法通过以下步骤查找单词:
key_calculator
使用函数将目标词转换为键。- 使用搜索算法,例如二分搜索。
或者
您可以使用此语法随机访问任何密钥inven[key_calculator('Orange')]
。
推荐阅读
- ruby-on-rails - 活动存储 - 如何修改文件并重新保存
- magento2 - Valet-plus:如何使用 php7.2 或 php7.1 安装 mcrypt
- android - 使用 Ionic 3 构建 android 应用程序时出现 processDebugResources 错误
- python - 抓取隐藏在“阅读更多”下的数据的网站
- php - WordPress 中的 SVG 精灵:实现 SVG 精灵的最佳方式是什么?
- python - 更新旧 Python 代码 - CSV 读取和打印程序
- angular - 根据表单中的选择值隐藏/显示按钮
- react-native - React Native 如何在启动画面设置 Gif 图像?
- android - Android 解密 RSA 在有意义的结果之前返回抓取的代码
- opencl - opencl 中的 memcpy 等价物