Improves solution to Problem 47 in Python