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)))
#akshay reddy
ReplyDeleteimport 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)