Python: can someone point out what is wrong?


  • 0
    Z

    I am practicing python. the solution works on my other python terminal. But for some reason, it won't pass the [[0,1]] matrix. the result is weird. Here is my code. I appreciate any comment.

    i) I created an empty matrix with the same dimension and filled it with all zeros.
    ii) I tested each row or column to see if the product of all element equals to 0. If not, I add that row or column number into a list, row or col.
    iii) I assigned the elements indicated by the positions from the list to the empty matrix and fill in all the non-zeros.

    Thanks.

    class Solution(object):
    def setZeroes(self, matrix):

        self.matrix = matrix
        
        
        m = len(self.matrix)
        n = len(self.matrix[0])
        temp = [ [0]*n for i in range(m)]
        
        row =[]
        col = []
        
        
        for i in range(m):
            p=1
            for j in range(n):
                p *= self.matrix[i][j]
            if p!=0:
                row.append(i)
      
        for j in range(n):
            q=1
            for i in range(m):
                q *=self.matrix[i][j]
            if q!=0:
                col.append(j)
        
        if row == [] or col==[]:
            matrix = [[0]*n for i in range(m)] 
        else:
            for h in row:
                for k in col:
                    num = self.matrix[h][k]
                    temp[h][k] = num 
                    
            matrix = temp

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.