Improved Python solution for problem 4