Last active
March 31, 2016 14:26
-
-
Save mofax/827ba226a85186f4e6ceb7a8e77ec846 to your computer and use it in GitHub Desktop.
absolute difference of NxN square matrix diagonals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
""" | |
abs_diag_sum | |
a function to find the absolute difference of the sum of diagonals of an NxN square matrix | |
where the square matrix is represented as list of lists | |
such that the square matrix | |
2 5 6 | |
7 5 8 | |
9 6 7 | |
would be represented as [[2, 5, 6], [7, 5, 8], [9, 6, 7]] | |
and the difference of sum of diagonals then would be | |
(2 + 5 + 7) - (6 + 5 + 9) = 6 | |
@Alloys Mila | |
""" | |
def abs_diag_sum(matrix): | |
if type(matrix) is list: | |
# initialize the sum of each diagonal to zero | |
primary_diagonal = 0 | |
secondary_diagonal = 0 | |
for i in range(len(matrix)): | |
row = matrix[i] | |
# check that the length of the row is equal to the lenth of the matrix | |
# because for an NxN square matrix rows = columns | |
if len(row) is len(matrix): | |
# bump the sum | |
primary_diagonal = primary_diagonal + int(row[i]) | |
secondary_marker = (len(row) - i) - 1 | |
secondary_diagonal = secondary_diagonal + int(row[secondary_marker]) | |
else: | |
print('make sure to provide a valid square matrix') | |
return abs(primary_diagonal - secondary_diagonal) | |
else: | |
print('expecting the input to be a list got ' + type(c) + ' instead') | |
# test | |
sum = abs_diag_sum([[2, 5, 6], [7, 5, 8], [9, 6, 7]]) | |
print(sum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment