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 =0for a,b in permutations(l, 2):
        if (a - b) <=d and(b - a) <= d:
            ctr += 1return ctr

And here's how I'd do it:

defclose_pairs(l, d):
    returnsum(abs(a-b) <= d for a, b in permutations(l, 2))

Solution 2:

from itertools import permutations
defnearest_pairs(a, b):
    for m, n in permutations(a, 2):
        ifabs(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:

defnearest_pairs_count(a, b):
    c, l = 0, len(a)
    for i inrange(l):
        for j inrange(i + 1, l):
            ifabs(a[i] - a[j]) <= b:
                c += 2return c

Post a Comment for "Number Of Pairs"