Improved and corrected Python solution for problem 4