Corrected Python solution for problem 6