Solves Problem 8 in Python