Answer to Question #316615 in Python for babu

Question #316615

question: find the perimeter of the given matrix?


input1:-

3 3

1 2 3

4 5 6

7 8 9

output :-

1+2+3+4+6+7+8+9 = 40


input2:-

4 4

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

output:-

1+2+3+4+5+8+9+12+13+14+15+16= 102





1
Expert's answer
2022-03-23T13:44:48-0400
import numpy as np
import re

def check_input(in_put, len_input=2):
    x = re.findall(r'\d+', in_put)
    if len(x) == len_input:
        return True
    else:
        return False


def set_matrix(is_generate=True):
    raw = input('Input:-\n')
    if check_input(raw, len_input=2):
        m, n = list(map(int, raw.split()))
        if is_generate:
            mat = np.arange(1, m * n + 1).reshape(m, n)
            print('Generated')
            print(mat)
        else:
            mat = []
            for i in range(m):
                row = input()
                if check_input(row, len_input=n):
                    mat.append(list(map(int, row.split())))
                else:
                    raise Exception('Wrong row elements number')
            print('Entered')
            mat = np.array(mat)

        return mat
    else:
        raise Exception('Incorrect length or type of input')


def calc_perimeter(mat):
    up = mat[0, :]
    down = mat[-1, :]
    left = mat[1:-1, 0]
    right = mat[1:-1, -1]
    print('output:-')
    final = np.concatenate((up, left, right, down), axis=0)
    for i, v in enumerate(final):
        if i == len(final)-1:
            print(f'{v}', end=' ')
        else:
            print(f'{v}+', end='')
    print('=', sum(final))


mat = set_matrix(is_generate=False)
#mat = set_matrix()
calc_perimeter(mat)

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