Mihai Stefanescu
Mihai Stefanescu

Reputation: 39

Returning indexes of pairs of values

I'm trying to create a function that takes a list of numbers and a number b and will print the indexes of all pairs of values in the list that sum to b. My code so far includes the list operations

def pairSum(a,b):
    for i in a:
        for j in a:
            if i+j==b: 

it should run like this

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

Note that it returns the positions of the values in the list and not the actual numbers and this is what I cannot wrap my head around.

Upvotes: 0

Views: 51

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61032

Use enumerate

for i, x in enumerate(a): #i is index of x
    for j, y in enumerate(a[i+1:], start=i+1): #j is index of y
        if x+y == b:
            print(i, j)

The a[i+1:] is to prevent duplicates and to stop values from being added to themselves.

Documentation: https://docs.python.org/3/library/functions.html#enumerate

Upvotes: 1

Related Questions