I'm trying to complete "Two Sum", which goes as such:
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).
Efficiency of my code aside, this is what I have so far:
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
It works for inputs such as:
>>> two_sum([1,2,3,4,5,6,7,8,9,10], 11)
(0, 9)
But when I try a list of numbers that have recurring numbers that add up to the target, the code doesn't work:
>>> two_sum([2, 2], 4)
False
The code, for some reason that I cannot figure out, does not reach index [1] of the list, and thus returns False
.
Why is that?
CodePudding user response:
''' return will break the loop and come out of function, so first you need to complete the cycle, store the result in list as you cant write to tuple, once your loop gets completed convert list to tuple and 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
CodePudding user response:
The list method index()
always returns the first occurence of an item in a list, so numbers.index(i) != numbers.index(t)
evaluates to 1 != 1
which is False
.
You should use the builtin enumerate()
to store the indices while looping over the list.
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
CodePudding user response:
Your code looks fine except this part:
if numbers.index(i) != numbers.index(t):
return (numbers.index(i), numbers.index(t))
return False
Because the index method returns only the first occurrence of a value, i and t are always the same. It will always return false. The index of the value 2 is always 0 in the list even though there is another 2 at index 1.
Source: https://www.w3schools.com/python/ref_list_index.asp
What you want to do is this:
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
This way the index is not associated with the value