Python implementation of problem 8.