【发布时间】:2019-02-25 05:24:55
【问题描述】:
我一直在尝试将重复键添加到我的 python 字典(表)中,以解决“两个总和”问题。
给定一个整数数组,返回两个数字的索引,使它们相加为特定目标。
我现在已经意识到这是不可能做到的,并且很感激任何关于如何在没有蛮力的情况下解决这个问题的想法或建议。请记住,我这周开始尝试学习 Python。所以我很抱歉有一个简单的解决方案
numbers = [0, 0, 0, 0, 0, 0, 0] # initial list
target = 6 # The sum of two numbers within list
# Make list into dictionary where the given values are used as keys and
actual values are indices
table = {valueKey: index for index, valueKey in enumerate(numbers)}
print(table)
>>> {0: 6}
【问题讨论】:
-
欢迎来到stackoverflow!您的问题可能已经在这里有了答案:stackoverflow.com/questions/10664856
-
你可以使用元组列表(valueKey, index)
-
为什么需要添加重复键?
-
@khachik 好吧,我对重复键的推理是我会将值存储为键,将索引存储为实际值。然后我可以得到(目标 - 当前迭代)并查找结果。我现在知道这是不可能的,哈哈
标签: python python-3.x dictionary duplicates