ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
from collections import Counter
def pairs_eq(a, t):
    c = Counter(a)
    total = 0
    for x in c:
        y = t - x
        if x < y:
            total += c[x] * c[y]
        elif x == y:
            total += c[x] * (c[x] - 1) // 2
    return total
print(pairs_eq([1, 2, 2, 3, 3, 3, 4], 5), pairs_eq([2, 2, 2], 4))
  1. A. 6 3
  2. B. 7 3
  3. C. 7 2
  4. D. 8 3

Correct answer: B. 7 3

Count value pairs using multiplicities. 1 with 4 gives 1 pair, and 2 with 3 gives 2 x 3 = 6 pairs, for a total of 7. Three equal values 2 give C(3,2) = 3 pairs.

More Python Programming questions

Exams that ask this topic