Solving problem 3 using Python