Optimized problem 4 code.

Hope it helps!