Code

Combinations at Sea

itertools builds clever loops for you. Its functions return lazy iterators, so wrap them in list() to see everything.

from itertools import combinations, permutations, product, accumulate, chain

list(combinations("ABC", 2))  # [('A','B'), ('A','C'), ('B','C')]
list(permutations("AB"))      # [('A','B'), ('B','A')]  (order matters)
list(product("AB", [1, 2]))   # [('A',1), ('A',2), ('B',1), ('B',2)]
list(accumulate([3, 1, 4]))   # [3, 4, 8]  (running totals)
list(chain([1, 2], [3]))      # [1, 2, 3]  (one after another)
  • combinations: pick groups where order doesn't matter (pairs of crew mates).
  • permutations: every ordering (race finishing orders).
  • product: every pairing between two lists, like nested loops.
  • accumulate: running totals (or running max with func=max).

Others worth knowing: count() counts forever, cycle() repeats, and islice(it, n) takes the first n items of any iterator.

Assignment

  1. all_pairs(crew): return a list of every pair of crew members as tuples (order doesn't matter, no one pairs with themselves).
  2. running_fuel(amounts): return a list of running totals.
  3. all_routes(starts, ends): return a list of strings like "Amber->Fog" for every start/end combination, in order.