Round and round the robin goes

Recently I found it useful to implement a round-robin tournament. Here’s a little Python generator that produces schedules for you, for your enjoyment.

from collections import deque
def round_robin(size):
  if size < 2:
    yield []
    raise StopIteration

  teams = range(1, size)
  rounds = size - 1
  if size % 2:
    teams.append(None)
    rounds = rounds + 1
  roster = deque(teams)
  half = (len(roster) + 1)/2
  for round in range(rounds):
    positions = [0] + list(roster)
    backwards = positions[::-1]
    yield [(positions[i], backwards[i]) for i in range(half)]
    roster.rotate()