you are given an m*n matrix.write a program to compute the perimeter of the matrix and print the result.perimeter of a matrix is defined as the sum of all elements of the four edges of the matrix
m = no of rows
n = no of columns
Ex: [1 2 3 4
5 6 7 8
9 10 11 12]
Perimeter : 1+2+3+4+8+12+11+10+9+5 = 65
Note: take input from the user.
matrix=[]
print('Enter no of rows: ', end='')
m = int(input())
print('Enter no of columns: ', end='')
n = int(input())
print('Enter matrix (sep. space):')
for i in range(m):
a = input().split()
matrix.append([])
for j in range(n):
matrix[i].append(int(a[j]))
sum = 0
print('Perimeter: ', end='')
for j in range(0, n):
print(f'{matrix[0][j]}', end='')
if j < n:
print('+', end='')
sum = sum + matrix[0][j]
for i in range(1, m-1):
print(f'{matrix[i][n-1]}', end='')
if i < m-1:
print('+', end='')
sum = sum + matrix[i][n-1]
for j in range(n-1, -1, -1):
print(f'{matrix[m-1][j]}', end='')
if j > -1:
print('+', end='')
sum = sum + matrix[m-1][j]
for i in range(m-2, 0, -1):
print(f'{matrix[i][0]}', end='')
if i > 1:
print('+', end='')
sum = sum + matrix[i][0]
print(f'= {sum}')
Comments
Leave a comment