• + 0 comments

    By far not the best way, but I've tried to do it without regex:

    !/bin/python3

    import math import os import random import re import sys

    first_multiple_input = input().rstrip().split()

    n = int(first_multiple_input[0])

    m = int(first_multiple_input[1])

    matrix = []

    for _ in range(n): matrix_item = input() matrix.append(matrix_item)

    string = ""

    for j in range(m): for i in range(n): string += matrix[i][j]

    symb = ('!','@','#','$','%','&', ' ')

    temp_list = []

    for idx, c in enumerate(string): ((c in symb) == True and ((idx-1>=0 and string[idx-1] not in symb) == True or temp_list != [])) and temp_list.append(idx)

    try: item = temp_list[-1] == len(string)-1 and temp_list[-1] or -999

    while True:
        try:
            temp_list.remove(item)
            item-=1
        except Exception:
            break
    
    remove = []
    
    c = 0
    while True:
        try:  
            (temp_list[c+1] == temp_list[c]+1) and remove.append(string[temp_list[c]])
            (temp_list[c+1] != temp_list[c]+1) and remove.append(string[temp_list[c]] + "_")        
            c+=1
        except Exception:
            (temp_list[c] == temp_list[c-1]+1) and remove.append(string[temp_list[c]])
            (temp_list[c] != temp_list[c-1]+1) and remove.append(string[temp_list[c]] + "_")
            break
    
    remove = "".join(remove)
    remove = remove.split("_")
    
    for c in remove:
        string = string.replace(c, " ", 1)
    
    print(string)
    

    except Exception: # In case the themp_list is [], so we just return the original string print(string)