I build a function(A kind of puzzle) that counts from a matrix the number of valid count (Explanation below). The matrix is made up of 0,1.
Input-
- a matrix- list of lists
- row number
- column number
Output- valid count.
Valid Count - This is the number of cells that are in the same row and column that we got in the Input. where there is the digit 1 so the digit zero is not between them (between matrix[row][col] to those other cells).
for example-
matrix = [[1,0,1,1],[0,1,1,1],[1,0,1,0]] valid_count(matrix, 0, 0) → 1 valid_count(matrix, 1, 0) → 0 valid_count(matrix, 1, 2) → 5 valid_count(matrix, 1, 1) → 3 I wrote a function that works properly, the problem is that it is a bit long and not elegant in my opinion. I would love advice for improving runtime, shortening the code and writing it in a more elegant way.
my code:
def valid_count(matrix, row, col): if matrix[row][col] == 0: return 0 else: return 1 + valid_count_row_helper(matrix, row, col) + valid_count_col_helper(matrix, row, col) def valid_count_row_helper(matrix, row, col): # This function checks if there are valid cells along the requested row (we received in the input) count = 0 for i in range(row + 1, len(matrix)): # checking from matrix[row][col] to matrix[len(matrix)][col] -going up if matrix[i][col] != 0: count += 1 else: break for j in range(1,row+1): if matrix[row - j][col] != 0: # checking from matrix[row][col] to matrix[0][col] -going down count += 1 else: break return count def valid_count_col_helper(matrix, row, col): # This function checks if there are valid cells along the requested column (we received in the input) count = 0 for i in range(col + 1, len(matrix[0])): # checking from matrix[row][col] to matrix[row][len(matrix[0])] -going up if matrix[row][i] != 0: count += 1 else: break for j in range(1,col+1): if matrix[row][col - j] != 0: # checking from matrix[row][col] to matrix[row][0] -going down count += 1 else: break return count