def correlate(answer, guess):
  """Return the matching pattern for 'guess' at 'answer'.

  Returns a string of N characters:

    . = letter of guess does not occur in answer
    O = letter of guess occurs in answer but not in the right place
    X = letter is in the right place.

  Because O only counts for letters that haven't been
  indicated with another X or O yet, we have to cross off
  letters from the answer to make sure we don't count double.
  """
  assert len(answer) == len(guess)

  # Make answer mutable, so we can cross off lettres
  answer = list(answer)

  N = len(guess)

  ret = ['.'] * N

  # First do Xes
  for i in range(N):
    if guess[i] == answer[i]:
      ret[i] = 'X'
      answer[i] = '?' # Cross off

  # Then do Os
  for i in range(N):
    if ret[i] == '.': # Not guessed yet
      try:
        j = answer.index(guess[i])
        ret[i] = 'O'
        answer[j] = '?' # Cross off
      except ValueError:
        pass
  return ''.join(ret)