Skip to main content
 首页 » 编程设计

python之向 Python 字典添加重复键 ("Two Sum"问题)

2024年12月31日11shihaiming

<分区>

我一直在尝试向我的 python 字典(表)中添加重复的键,以解决“双和”问题。

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

我现在已经意识到这是不可能的,如果有任何关于如何在不使用蛮力的情况下解决这个问题的想法或建议,我将不胜感激。请记住我这周开始尝试学习 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}