Solution for problem 8 in Python