Monday, December 16, 2019

Matrix Script - Hacker Rank Solution

Matrix Script - Hacker Rank Solution

We can zip(*matrix) to read the matrix columnwise.
Using (?<=[A-Za-z0-9])([^A-Za-z0-9]+)(?=[A-Za-z0-9]) this regex we can substitute all non alphanumeric characters between two alphanumeric characters.

import re
matrix = []
N,M = map(int, raw_input().split())
for i in range(N):
    matrix.append(list(raw_input()))
print re.sub(r'(?<=[A-Za-z0-9])([^A-Za-z0-9]+)(?=[A-Za-z0-9])',' ',"".join("".join(decode) for decode in zip(*matrix)))


1 comment:

  1. #akshay reddy

    import re

    (N,M) = map(int, raw_input().strip().split())

    matrix = []

    for i in range(N):
    matrix.append(raw_input())

    phrase = ""

    for j in range(M):
    for i in range(N):
    phrase += str(matrix[i][j])


    print re.sub(r'\b[^a-zA-Z0-9]+\b', r' ', phrase)

    ReplyDelete

Powered by Blogger.