matrix_zeros.py 922 B

123456789101112131415161718192021222324252627282930313233
  1. # Write an algorithm such that if an element in an MxN matrix is 0,
  2. # its entire row and column is set to 0.
  3. import pytest
  4. import numpy as np
  5. from numpy.testing import assert_array_equal
  6. def test_matrix_zeros():
  7. case1 = np.zeros((3,3))
  8. case2 = np.array([[1,0,1],[2,3,0]])
  9. expect2 = np.zeros((2,3))
  10. assert_array_equal(matrix_zeros(case1), case1)
  11. assert_array_equal(matrix_zeros(case2), expect2)
  12. # test error message
  13. with pytest.raises(Exception):
  14. matrix_zeros([1,1])
  15. def matrix_zeros(matrix):
  16. r, c = matrix.shape
  17. if not r or not c:
  18. raise ValueError('Not a matrix!')
  19. r_ind, c_ind = [], []
  20. for i in range(r):
  21. for j in range(c):
  22. if matrix[i,j] == 0:
  23. r_ind.append(i)
  24. c_ind.append(j)
  25. for i in r_ind:
  26. matrix[i, :] = np.zeros(c)
  27. for i in c_ind:
  28. matrix[:, i] = np.zeros(r)
  29. return matrix