python - 如何找到任意两个数字的索引,其总和等于 Python 中的目标总和?

标签 python algorithm data-structures

我正在 testdome.com 上进行此测试以进行练习,但它未通过某些测试用例。谁能帮我指出代码中的逻辑错误?

这是我的代码的问题:

“编写一个函数,当传递一个列表和一个目标总和时,根据使用的时间高效地返回两个不同的从零开始的任意两个数字的索引,其总和等于目标总和。

如果没有两个数字,函数应该返回None

例如,find_two_sum([3, 1, 5, 7, 5, 9], 10) 应该返回包含以下任一索引对的单个元组:

  • 0 和 3(或 3 和 0),因为 3 和 7 的加法是 10。
  • 1 和 5(或 5 和 1),因为 1 和 9 的加法是 10。
  • 2 和 4(或 4 和 2),因为 5 和 5 的加法是 10。
def find_two_sum(numbers, target_sum):
    sss=list(dict.fromkeys(numbers))
    if (sss == None or len(sss) < 2): return None

    for item in sss:
        tesn=target_sum-item
        if tesn in sss: 
            if numbers.index(item)==numbers.index(tesn):
                continue
            else:
                return numbers.index(item),numbers.index(tesn)
    return None
print(find_two_sum([3, 1, 5, 7, 5, 9], 10))

他们有四个测试用例,我的代码只能通过前两个测试用例。

示例:错误答案(返回 [0,2] 因为索引 0 的 3 + 索引 3 的 7 是 10)
有解和无解的不同数字:错误答案
有和没有解决方案的重复数字:错误答案
大量数字的性能测试:错误答案

最佳答案

我对这个问题的看法:

def find_two_sum(lst, n):
    indices = {}
    for idx, num in enumerate(lst):
        indices.setdefault(num, []).append(idx)
    for k, v in indices.items():
        i = v.pop()
        if n - k in indices and indices[n-k]:
            return i, indices[n-k].pop()

print( find_two_sum([3, 1, 5, 7, 5, 9], 6) )
print( find_two_sum([3, 1, 5, 7, 5, 9], 10) )
print( find_two_sum([1, 2, 1, 8], 10) )
print( find_two_sum([5, 5], 10) )
print( find_two_sum([11], 10) )

打印:

(1, 4)
(0, 3)
(1, 3)
(1, 0)
None

关于python - 如何找到任意两个数字的索引,其总和等于 Python 中的目标总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57450616/

相关文章:

algorithm - 函数式编程中存在 "algorithms"吗?

algorithm - 任务/作业调度问题

java - 比较存储为 List 结构的 Hashmap 值

algorithm - 是否有任何允许并行加法的自然数代数表示?

python - 收到类型 xx 的未注册任务。该消息已被忽略并丢弃

python - 将大对象的方法传递给 imap : 1000-fold speed-up by wrapping the method

python - 即使使用最新的 Keras/Theano,ValueError : Invalid argument 'metric' passed to K. 也会起作用

python - 有没有更快的方法来遍历和删除 Pandas 数据框中的特定行?

c - 字符串 - 名字和姓氏按字母顺序排列,大写字母

C++数据结构执行索引列表