diagonal difference

mail@pastecode.io avatar
unknown
python
2 years ago
1.3 kB
6
Indexable
Never
# take dimensions input
num = int(input())

# main matrix list
matrix = []

# iterate in range of num and take input
for n in range(num):
	matrix_row = list(map(int, input().split()))
	# printed for checking
	# print(matrix_row)
	matrix.append(matrix_row)

# print(matrix)

# set sum_left_diagonal to 0 for adding later in list
sum_left_diagonal = 0
# set diagonal element start index to 0
diagonal_element_index = 0
# calculate sum of diagonal elements
for i in range(num):
	# printed for checking
	# print(matrix[row][col])
	sum_left_diagonal = sum_left_diagonal + matrix[diagonal_element_index][diagonal_element_index]
	diagonal_element_index += 1 

# print('Left Diagonal Sum:', sum_left_diagonal)

# set row to 0 for first index of matrix to hop to next row
row = 0
# set diagonal element sum to 0
sum_right_diagonal = 0
# iterate through the num in reverse order
for j in reversed(range(num)):
	sum_right_diagonal =  sum_right_diagonal + matrix[row][j]
	# print('Now on element:', matrix[row][j])
	# print('sum_right_diagonal:', sum_right_diagonal)
	row += 1

# print('Right Diagonal Sum:', sum_right_diagonal)

absolute_diagonal_difference = abs(sum_left_diagonal - sum_right_diagonal)

print(absolute_diagonal_difference)