Matrix Problem
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.
Input
The first line of input containing the positive integer.
The second line of input containing the positive integer.
The next N lines of input space-separated integers.
Explanation: The input should be
3
4
1 2 3 4
5 6 7 8
9 10 11 12
The output should be 1+2+3+4+8+12+11+10+9+5 = 65
Sample Input1
4
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sample Output1
1+2+3+4+8+12+16+15+14+13+9+5=102
matrix = []
print('Enter m: ', end='')
m = int(input())
print('Enter n: ', 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 i in range(m):
for j in range(n):
if (j == 0) | (j == n-1) | (i == 0) | (i == m-1):
sum = sum + matrix[i][j]
if (i != m-1) | (j != n-1):
print(f'{matrix[i][j]}+', end='')
else:
print(f'{matrix[i][j]}', end='')
print(f'={sum}')
Comments
Leave a comment