HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Diagonal difference

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
differencediagonalstackoverflow

Problem

Given


You are given a square matrix of size \$N×N\$. Calculate the absolute difference of the sums across the two main diagonals.

Input Format


The first line contains a single integer N. The next N lines contain N integers (each) describing the matrix.

Constraints


\$1\leq N \leq 100\$


\$−100 \leq A_{i} \leq 100\$

Solution

def diagonal_difference(matrix):
    l = sum(matrix[i][i] for i in range(N))
    r = sum(matrix[i][N-i-1] for i in range(N))
    return abs(l - r)

matrix = []
N = input()
for _ in range(N):
    matrix.append(map(int, raw_input().split()))

print diagonal_difference(matrix)


Is there more elegant solution for the given problem. Also, I am getting intuition that I can use reduce, is that possible?

Solution

Instead of indexing to access the rows, you could use iteration:

l = sum(row[i] for i, row in enumerate(matrix))


Instead of doing two passes over matrix to calculate l and r, you could accumulate the difference in one pass: (note also negative indexing from end of list)

difference = sum(row[i] - row[-i-1] for i, row in enumerate(matrix))
return abs(difference)


The single-pass approach would also allow you to process input line by line, instead of storing the whole matrix in memory.

Code Snippets

l = sum(row[i] for i, row in enumerate(matrix))
difference = sum(row[i] - row[-i-1] for i, row in enumerate(matrix))
return abs(difference)

Context

StackExchange Code Review Q#105242, answer score: 10

Revisions (0)

No revisions yet.