Python code for problem 3