Answer to Question #231583 in Python for bhuvana

Question #231583

Given a M x N matrix, write a program to print the matrix after ordering all the elements of the matrix in increasing order.For example, if the given M is 3 and N is 3, read the inputs in the next three lines if the numbers given in the next three lines are the following.

1 20 3
30 10 2
5 11 15
1
Expert's answer
2021-09-12T02:58:28-0400
def ReadMatrix(m, n):
    M = []
    for i in range(m):
        s = input()
        s = s.split()
        row = []
        for j in range(n):
            row.append(int(s[j]))
        M.append(row)
    return M

def SortMatrix(M):
    m = len(M)
    n = len(M[0])
    L = []
    for row in M:
        L += row
    L.sort()
    M = []
    for i in range(m):
        M.append(L[n*i:n*(i+1)])
    return M

def PrintMatrix(M):
    for row in M:
        for x in row:
            print(x, end=' ')
        print()

def main():
    m = int(input())
    n = int(input())
    M = ReadMatrix(m, n)
    print()
    M = SortMatrix(M)
    PrintMatrix(M)

if __name__ == '__main__':
    main()

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