Find perimeter of a matrix without using numpy
Input1:
1 2 3
4 5 6
7 8 9
Output: 40
Input2:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output: 102
#!usr/bin/python
import numpy as np
# read matrix
mtx = np.arange(1, 10).reshape(3, 3)
print(mtx)
# calc size of the matrix
n = len(mtx);
# calc perimeter of the matrix
perimeter = sum(mtx[0]) + sum(mtx[n-1])
mtx.transpose()
perimeter = perimeter + sum(mtx[0]) + sum(mtx[n-1])
perimeter = perimeter - mtx[0][0] - mtx[0][n-1] - mtx[n-1][0] - mtx[n-1][n-1]
# print the answer
print(perimeter)
Comments
Leave a comment