Solves Problem 31 in Python