Easy: Warm-Ups · Problem 16 of 82

Team Pairings

EasyStandard LibraryPython

Write team_pairings(names) that returns a list of all different pairs of names, as tuples (a, b), where a comes before b in the input list. The pairs come in this order: by the position of the first name, then by the position of the second.

team_pairings(["Ann", "Bob", "Cy"]) is [("Ann", "Bob"), ("Ann", "Cy"), ("Bob", "Cy")].

Understand the problem

Count and decide what a pair is.

How many different pairs can you make from 5 names? (A pair of Ann and Bob is the same as Bob and Ann.)

5 x 4 / 2 = 10. For n names the number of pairs is n x (n - 1) / 2. Ordered pairs (Ann, Bob) and (Bob, Ann) would count twice, so the 2 is divided out.

What is the difference between itertools.combinations(x, 2) and itertools.permutations(x, 2)?

  1. None
  2. Combinations ignore order, so each pair appears once; permutations count both orders
  3. Combinations are faster

Combinations ("choose 2") give each group once. Permutations ("arrange 2") give each group in every order, twice as many here. A pair of people is a combination.

Write the solution

Return a list of tuples.

def team_pairings(names):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Which function of the standard library generates groups of a given size, each group once?

Hint 2: the shape of the answer

itertools.combinations(names, 2) gives an iterator of tuples; wrap it in list(...).

Reflect

Solution

from itertools import combinations

def team_pairings(names):
    return list(combinations(names, 2))

Another way: two loops

def team_pairings(names):
    pairs = []
    for i in range(len(names)):
        for j in range(i + 1, len(names)):
            pairs.append((names[i], names[j]))
    return pairs

What this tests: knowing itertools (combinations, permutations, product), and the difference between a group where order matters and one where it does not.

The four tools: product(a, b) all ordered choices from several lists, permutations(x, r) ordered arrangements, combinations(x, r) unordered groups, combinations_with_replacement(x, r) groups where an item can repeat.

Both versions are O(n squared), because there are that many pairs. The loop version shows what combinations does: the inner loop starts at i + 1, so no pair repeats.

They return iterators: lazy, so a million combinations do not use memory until you ask for them. Wrap in list only when you need the list.

What an interviewer might ask next: How many teams of 3 can be formed from 20 people, and why must you not print them all? (math.comb(20, 3) is 1140; math.comb(100, 10) is over 17 trillion.)