
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
all_pairs(crew): return a list of every pair of crew members as tuples (order doesn't matter, no one pairs with themselves).running_fuel(amounts): return a list of running totals.all_routes(starts, ends): return a list of strings like"Amber->Fog"for every start/end combination, in order.
all_pairs(crew): return a list of every pair of crew members as tuples (order doesn't matter, no one pairs with themselves).running_fuel(amounts): return a list of running totals.all_routes(starts, ends): return a list of strings like"Amber->Fog"for every start/end combination, in order.
main.py Python sleeping
Press Run to try your code, then Check to test it.