ziggy - 7 months ago 39

Python Question

I am trying to write a python functions that takes in a list or array. if any two numbers in the list or array equal to zero, I want to return the positions of those two numbers.

Here is what I have so far. I loop through the list and have a nested loop of the same list to test if the outer iterator plus the nested iterator == 0: if yes then I am trying to return the positions of the two numbers that == 0. but it just gives me the actual two numbers instead. whats strange is the output below (even though it is not what I want) should be (3,-3). Any input would be greatly appreciated

`def twosum(nums):`

for x in nums:

for y in nums:

if x + y == 0:

return nums[x],nums[y]

print twosum([1, 3, 5, -3])

output = (-3, 3)

Answer

You have to use `enumerate()`

while iterating over the list like:

```
def twosum(nums):
for i, x in enumerate(nums):
for j, y in enumerate(nums):
if x + y == 0:
return i, j
```

However this logic can be further optimised as:

```
def twosum(nums):
for i, x in enumerate(nums):
if -x in nums[i:]: # if negative of the number exists in non-iterated list
return x, -x
```

Source (Stackoverflow)