Solving problem 5 using python