Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added skeleton for solution of cci/1.8 #8

Merged
merged 2 commits into from
Oct 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 37 additions & 6 deletions cci/1.8.zero_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
column are set to 0.
'''

from typing import List


def zero_matrix(a, m, n):
R'''
My first `reasonnable` approach. Although I feel it is not good.
R"""
My first `reasonable` approach. Although I feel it is not good.
O(M^2N + MN^2) time just for O(1) space :(. It's not good. We can make it O(MN) with O(M + N) space.
Here, the obvious errors I nearly made were: 1. To think that once I find a zero on a row I just have to zero the remaining values: Nope, I have to circle through all of them to zero their column
2. I also have to zero left from a zero's row, and up from a zero's column.
'''
"""
if not a:
return

Expand Down Expand Up @@ -74,16 +77,44 @@ def nullify_row(i):
else:
for j in a[0]:
if j == 0:
set_origin = True # Be very careful, the column has already been set to 0,the ROW SHOULD NOT, only (0,0)
set_origin = True # Be very careful, the column has already been set to 0,the ROW SHOULD NOT, only (0,0)
for i in range(m):
if a[i][0] == 0:
set_origin = True # Be very careful, the row has already been set to 0,the COLUMN SHOULD NOT, only (0,0)
set_origin = True # Be very careful, the row has already been set to 0,the COLUMN SHOULD NOT, only (0,0)

if set_origin:
a[0][0] = 0

return a


def matrix_zero(a: List):
def zero_row(row):
for col in range(len(a[row])):
a[row][col] = 0

def zero_column(col):
for row in range(len(a)):
a[row][col] = 0

rows_to_zero = []
columns_to_zero = []
m = len(a)
for i in range(m):
n = len(a[i])
for j in range(n):
if a[i][j] == 0:
rows_to_zero.append(i)
columns_to_zero.append(j)

for r in rows_to_zero:
zero_row(r)

for c in columns_to_zero:
zero_column(c)


a = [[1, 2, 0], [6, 5, 4], [7, 0, 9]]
a = zero_matrix_auth(a, len(a), len(a[0]))
# a = zero_matrix_auth(a, len(a), len(a[0]))
matrix_zero(a)
print(a)