The Ultimate Hat Puzzle

This is the ultimate induction puzzle, presented using code written in Python.