Skip to content Skip to sidebar Skip to footer

Number Of Pairs

I am trying to write a code that takes m. a, a list of integers n. b, an integer and returns the number of pairs (m,n) with m,n in a such that |m-n|<=b. So far, I've got thi

Solution 1:

Yours doesn't make sense. No idea what you're trying with len(a, b), but it's not even allowed, since len takes only one argument. And returning something just when you found the first counting pair? Here's a fix:

def close_pairs(l, d):
    ctr = 0
    for a,b in permutations(l, 2):
        if (a - b) <= d and (b - a) <= d:
            ctr += 1
    return ctr

And here's how I'd do it:

def close_pairs(l, d):
    return sum(abs(a-b) <= d for a, b in permutations(l, 2))

Solution 2:

from itertools import permutations
def nearest_pairs(a, b):
    for m, n in permutations(a, 2):
        if abs(m - n) <= b:
            yield (m, n)
>>> list(nearest_pairs([1, 2, 5], 3))
[(1, 2), (2, 1), (2, 5), (5, 2)]
>>> list(nearest_pairs([1, 2, 5], 2))
[(1, 2), (2, 1)]

If you just want the count:

def nearest_pairs_count(a, b):
    c, l = 0, len(a)
    for i in range(l):
        for j in range(i + 1, l):
            if abs(a[i] - a[j]) <= b:
                c += 2
    return c

Post a Comment for "Number Of Pairs"