Solves Problem 16 in Python