[HackerRank] Diagonal Difference

This was a simple one too but I’m glad to have problems I feel qualified to handle. This problem is finding the difference between the sums of the diagonals of a matrix.

I started with a test:

print(calculate_diff_of_diagonals(arr, n) == 15)
print("expected:\n%s\nresult:\n%s" % (15, calculate_diff_of_diagonals(arr, n)))

Luckily tests are super easy when dealing with math problems. I threw in a boolean just to make it clear if things were working or not. So this would throw an answer like:

False

expected:

15

result:

0

It really was helpful having the test available as I had to work out the actual calculate_diff_of_diagonals method. The hard part was not the diagonals of left-to-right, that works well with the way for-loops work: take the nth list and the nth value from that list.

It was right-to-left that was hard. You want to take the nth list and the last value minus n (also minus one because indexing starts at zero).

### Like this:

Like Loading...

*Related*