Solves Problem 47 (slowly) in Python