python solution adopted from problem 16 for problem 20