Skip to content

Instantly share code, notes, and snippets.

@dudepare
Created August 19, 2016 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudepare/e73458aff49348d85b3e9e60868570c3 to your computer and use it in GitHub Desktop.
Save dudepare/e73458aff49348d85b3e9e60868570c3 to your computer and use it in GitHub Desktop.
Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
class Matrix:
@staticmethod
def zero(M, m, n):
"""Zeroes out the whole row and column if one elements is found to be zero.
Args:
M (array) of m rows and n columns
m (int) of rows
n (int) of columns
Returns:
M (array) modified with zeroed out rows/columns if applicable
"""
row = [0] * m
col = [0] * n
for i in range(m):
if 0 in M[i]:
row[i] = 1
for j in range(n):
if M[i][j] is 0:
col[j] = 1
for x in range(m):
if row[x] == 1:
M[x] = [0] * n
for y in range(n):
if col[y] == 1:
for z in range(m):
M[z][y] = 0
return M
import unittest
class TestZeroMatrix(unittest.TestCase):
def test_empty(self):
M = []
self.assertEqual(M, Matrix.zero(M, 0, 0))
def test_no_zeroes(self):
M = [
[1, 2],
[2, 1]
]
self.assertEqual(M, Matrix.zero(M, 2, 2))
def test_one_zero(self):
M = [
[0, 2],
[2, 1]
]
R = [
[0, 0],
[0, 1]
]
self.assertEqual(R, Matrix.zero(M, 2, 2))
def test_two_zeroes(self):
M = [
[0, 2],
[2, 0]
]
R = [
[0, 0],
[0, 0]
]
self.assertEqual(R, Matrix.zero(M, 2, 2))
def test_no_zero_m_by_n(self):
M = [
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7]
]
R = [
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7]
]
self.assertEqual(R, Matrix.zero(M, 5, 6))
def test_one_zero_m_by_n(self):
M = [
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 0, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 4, 5, 6, 7]
]
R = [
[2, 2, 0, 5, 6, 7],
[2, 2, 0, 5, 6, 7],
[0, 0, 0, 0, 0, 0],
[2, 2, 0, 5, 6, 7],
[2, 2, 0, 5, 6, 7]
]
self.assertEqual(R, Matrix.zero(M, 5, 6))
def test_multiple_0h_m_by_n(self):
M = [
[2, 2, 4, 5, 0, 7],
[2, 2, 4, 5, 6, 7],
[2, 2, 0, 5, 6, 7],
[2, 2, 4, 5, 6, 7],
[2, 0, 4, 5, 6, 7]
]
R = [
[0, 0, 0, 0, 0, 0],
[2, 0, 0, 5, 0, 7],
[0, 0, 0, 0, 0, 0],
[2, 0, 0, 5, 0, 7],
[0, 0, 0, 0, 0, 0]
]
self.assertEqual(R, Matrix.zero(M, 5, 6))
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment