solution to problem 31 in python