Answer to Question #314508 in Python for Mahesh

Question #314508

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



1
Expert's answer
2022-03-19T13:57:23-0400
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}') 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS