Don't you think there can be a better approach to this problem?
"Better" is a subjective concept. Some could call better this approach:
def odd_cells(n, m, indices): matrix = [[0] * m for _ in range(n)] for (ri, ci) in indices: for col in range(len(matrix[ri])): matrix[ri][col] ^= 1 for row in matrix: row[ci] ^= 1 return sum([sum(line) for line in matrix])
You can say it's better because it's shorter and faster. But it's much harder to read. If I am asked to maintain it, I would prefer much more TK's approach.
Or something like this:
def odd_cells(n, m, indices): matrix = init_matrix(n, m) for (ri, ci) in indices: increment_matrix(matrix, ri, ci) return sum_odds(matrix) def init_matrix(rows, columns): return [[0] * columns for _ in range(rows)] def increment_matrix(matrix, ri, ci): for col in range(len(matrix[ri])): matrix[ri][col] += 1 for row in matrix: row[ci] += 1 def sum_odds(matrix): odds = 0 for line in matrix: odds += sum([(cell % 2) for cell in line]) return odds
A lot more code, but way easier to read and understand, in my opinion.
Therefore, I ask you the same: don't you think there can be a better approach to this problem? How would you solve it?
I believe that there is a solution use only 4 numbers: number of columns (rows) which have even (odd) cells on each. Need time to test it...
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Don't you think there can be a better approach to this problem?
"Better" is a subjective concept. Some could call better this approach:
You can say it's better because it's shorter and faster. But it's much harder to read. If I am asked to maintain it, I would prefer much more TK's approach.
Or something like this:
A lot more code, but way easier to read and understand, in my opinion.
Therefore, I ask you the same: don't you think there can be a better approach to this problem? How would you solve it?
I believe that there is a solution use only 4 numbers: number of columns (rows) which have even (odd) cells on each. Need time to test it...