Solve problem 31 using Python.