I have a code where I zero a column or row if it contains zero , I have my own function but when I use it it returns None , I made a copy of my matrix and performed changes on it and then I converted the values to the original one and yet I still get no return . my function shouldn’t return values only update the matrix values. here’s the code:
JavaScript
x
18
18
1
def ConvertMatrix(NumOfRows,M):
2
for i in range(numOfRows):
3
Col=len(M[i])
4
M1=[[M[i][j] for j in range(Col)] for i in range(numOfRows)]
5
for i in range(numOfRows):
6
for j in range(Col):
7
if M[i][j]==0:
8
for n in range(Col):
9
M1[i][n]=0
10
for k in range(numOfRows):
11
M1[k][j]=0
12
M=[[M1[i][j] for j in range(Col)] for i in range(numOfRows)]
13
14
numOfRows = int(input())
15
M = [[int(item) for item in input().split(' ')] for i in range(numOfRows)]
16
M=ConvertMatrix(numOfRows,M)
17
print(M)
18
Advertisement
Answer
ConvertMatrix(numOfRows, M)
does not return anything which means it implicitly returns None
. Hence
JavaScript
1
2
1
M = ConvertMatrix(numOfRows, M)
2
turns M
into None
. There are two changes you should apply in order to make this mutation function approach work:
Change the last line in the function to:
JavaScript
1
4
1
M[:] = [[M1[i][j] for ]
2
# slice assignment mutates the passed list object ...
3
# otherwise you are just rebinding a local variable
4
Do not assign the function result:
JavaScript
1
4
1
# ...
2
ConvertMatrix(numOfRows, M)
3
print(M)
4