Better solution for problem 8