Final solution. Optimized using numpy arrays
Test Cases