Ted Idzikowski Ted Idzikowski - 8 months ago 44
Python Question

Creating a function pair_all() that returns the position of the pairs of the list that sum up to an integer?

How do you implement a function pair_all() that takes as input a list of distinct integers 1st and then an integer n, and prints the indexes of all pairs of values in 1st that sum up to n?

Expected result:

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

Here's what I did:

def pair_all(l,s):
i = 0
j = len(l)-1
for x in range(len(l)*len(l)):
if float(i) < float(len(l)/2):
if (l[i] + l[j] == s):
print(i,end=' ')
i += 1
elif (l[i] + l[j] < s):
j += 1
elif (l[i] + l[j] > s):
j -= 1


You just have to iterate through all the values and check for the remaining values:

def pairSum(l, total):
    for i, x in enumerate(l):
        for j, y in enumerate(l[i+1:], start=i+1):
             if x+y == total:
                 print(i, j)