Snow 8 years ago
parent
commit
db16f69c6e
2 changed files with 36 additions and 0 deletions
  1. 33 0
      arrays-and-strings/matrix-zeros.py
  2. 3 0
      arrays-and-strings/remove-duplicates.py

+ 33 - 0
arrays-and-strings/matrix-zeros.py

@@ -0,0 +1,33 @@
+# Write an algorithm such that if an element in an MxN matrix is 0,
+# its entire row and column is set to 0.
+
+import pytest
+import numpy as np
+from numpy.testing import assert_array_equal
+
+def test_matrix_zeros():
+    case1 = np.zeros((3,3))
+    case2 = np.array([[1,0,1],[2,3,0]])
+    expect2 = np.zeros((2,3))
+    assert_array_equal(matrix_zeros(case1), case1)
+    assert_array_equal(matrix_zeros(case2), expect2)
+    # test error message
+    with pytest.raises(Exception):
+        matrix_zeros([1,1])
+
+def matrix_zeros(matrix):
+    r, c = matrix.shape
+    if not r or not c:
+        raise ValueError('Not a matrix!')
+
+    r_ind, c_ind = [], []
+    for i in range(r):
+        for j in range(c):
+            if matrix[i,j] == 0:
+                r_ind.append(i)
+                c_ind.append(j)
+    for i in r_ind:
+        matrix[i, :] = np.zeros(c)
+    for i in c_ind:
+        matrix[:, i] = np.zeros(r)
+    return matrix

+ 3 - 0
arrays-and-strings/remove-duplicates.py

@@ -15,6 +15,9 @@ def test_remove_duplicates():
 
 pytest.main()
 
+# use two indicies to track non-duplicates in place.
+# time complexity: O(n^2)
+# space complexity: O(n)
 def remove_duplicates(input):
     len_input = len(input)
     if len_input <= 1: