Solve Problem 12 in Python