ziggy
ziggy

Reputation: 1538

Python list: if a pair of numbers equals 0 return the positions of the elements

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)

Upvotes: 0

Views: 431

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

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:]:  # check '-'ive of the number in non-iterated list
            return x, -x

Upvotes: 3

wbrugato
wbrugato

Reputation: 1469

You would do return nums.index(x), nums.index(y)

Upvotes: 1

Related Questions