Python - Problem 7

First attempt at solving problem 7. Probably fairly inefficient.