Python code to solve a puzzle