Check if column or diagonal in matrix = x (Without Numpy)

后端 未结 2 1445
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 10:10

I can use this code to check if a row in a matrix = x:

q = [[1,2,1],[1,2,1],[2,1,2]]
answer = [sum(row) for row in q]
for i in range(0, len(q)):
    if answe         


        
2条回答
  •  甜味超标
    2021-01-07 10:50

    How about this? Works for an arbitrary shape of q

    def check_col_diag (q, x):
        """
        Returns:
        0 if there was a column,
        1 if there was a row,
        2 if there was a diagonal on 1st direction
        3 if there was a diagonal on 2nd direction
        """
    
        # Get a mask to store the positions
        # on each row of q where q == x
        mask = q
        for row_ix in range(len(q[0])):
            for elem_ix in range(len(q[1])):
                if q[row_ix][elem_ix] == x:
                    mask[row_ix][elem_ix] = 1
                else:
                    mask[row_ix][elem_ix] = 0
    
        # Check rows
        c = [1]*len(q[0])
        for row in mask:
            # element-wise list multiplication
            c = [a*b for a,b in zip(c,row)]
        # Return 0 if there was a column
        if any(c):
            return 0
    
        # Check columns 
        c = [1]*len(q[1])
        # Iterate through rows of transposed list
        _q = list(map(list, zip(*mask)))
        for row in _q:
            c = [a*b for a,b in zip(c,row)]
        # Return 1 if there was a row
        if any(c):
            return 1
    
        # Check diagonal 1
        c = 1
        for row_ix in range(len(q[0])):
            c *= mask[row_ix][row_ix]
        # Return 2 if there was a 1st diagonal
        if c == 1:
            return 2
    
        # Check diagonal 2
        c = 1
        for row_ix in range(len(_q[0])):
            c *= mask[row_ix][row_ix]
        # Return 3 if there was a 2nd diagonal
        if c == 1:
            return 3
    
    
    q = [[1,2,1],[1,2,1],[2,1,2]]
    v = check_col_diag (q, 1)
    

提交回复
热议问题