Two-Sum函数不适用于列表中的重复元素



我正在尝试完成"二和";,如下所示:

编写一个函数,该函数接受一个数字数组(用于测试的整数(和一个目标数字。它应该在数组中找到两个不同的项,当它们加在一起时,就会给出目标值。然后,这些项的索引应该在元组中返回,如so:(index1,index2(。

撇开我的代码的效率不谈,这就是我迄今为止所拥有的:

def two_sum(numbers, target):
for i in numbers:
for t in numbers:
if i + t == target:
if numbers.index(i) != numbers.index(t): 
return (numbers.index(i), numbers.index(t))
return False

它适用于以下输入:

>>> two_sum([1,2,3,4,5,6,7,8,9,10], 11)
(0, 9)

但是,当我尝试一个具有重复数字的数字列表,这些数字加起来就是目标时,代码不起作用:

>>> two_sum([2, 2], 4)
False

由于某些我无法理解的原因,代码没有到达列表的索引[1],因此返回False

为什么?

列表方法index()总是返回列表中项目的第一个出现,因此numbers.index(i) != numbers.index(t)的计算结果为1 != 1,即False

您应该使用内置的enumerate()来存储索引,同时在列表上循环。

def two_sum(numbers, target):
for i, number_a in enumerate(numbers):
for j, number_b in enumerate(numbers):
if number_a + number_b == target and i != j:
return (i, j)
return False

''return将打破循环并退出函数,因此首先您需要完成循环,将结果存储在列表中,因为您无法写入元组,循环完成后,将列表转换为元组并返回''

def two_sum(numbers, target):
result = []
for i in numbers:
for t in numbers:
if (i + t == target) and (numbers.index(i) != numbers.index(t)):
result.append(i)
result.append(t)
if (len(result)> 0):
return tuple(result)
else:
return False

您的代码看起来不错,除了以下部分:

if numbers.index(i) != numbers.index(t): 
return (numbers.index(i), numbers.index(t))
return False

因为index方法只返回值的第一次出现,所以i和t总是相同的。它总是返回false。值2的索引在列表中始终为0,即使在索引1处还有另一个2。

来源:https://www.w3schools.com/python/ref_list_index.asp

你想做的是:

def two_sum(numbers, target):
i_index = 0
t_index = 0
for i in numbers:
for t in numbers:
if i + t == target:
if i_index != t_index:
return (i_index, t_index)
t_index +=1
i_index +=1
return False

这样,索引就不会与值相关联

def pairs_sum_to_target(list1, list2, target):
'''
This function is about a game: it accepts a target integer named target and 
two lists of integers (list1 and list2). 
Then this function should return all pairs of indices in the form [i,j] 
where list1[i] + list[j] == target.
To summarize, the function returns the pairs of indices where the sum of 
their values equals to target.
Important: in this game list1 and list2 will always have the same number of 
elements and returns the pairs in that order.
'''
pairs = [] #make a list, which is empty in the beginning. But store the sum pairs == target value. 
#loop for all indices in list1 while looping all the same indices in list2 and comparing if the sum == target variable. 
for i, value1 in enumerate (list1): 
for j, value2 in enumerate(list2): 
if value1 + value2 == target: ## if the value of element at indice i + value of element at indice j == target, then append the pairs to list pairs []- in order.
pairs.append(i,j)
return pairs

简单输入#1

"""This is one example of input for list1, list2, and target. In order to properly test this function"""
list1 = [1,-2,4,5,9]
list2 = [4,2,-4,-4,0]

最新更新