DEV Community

Discussion on: Daily Challenge #118 - Reversing a Process

colorfusion profile image
Melvin Yeo

In python

import re

def decode(str):
    # check whether input string is valid
    if (first_digit :="[a-zA-Z]", str)) is None:
        return "Impossible to decode"
        # extract the integer and text from string
        decode_num = int(str[0:first_digit.start()])
        text = str[first_digit.start():]

    result_str = ""

    # loop through all characters to decode string
    for char in text:
        index = ord(char) - ord('a')
        found = False
        # loop through all alphabets to decode string
        for num in range(0, 26):
            if num * decode_num % 26 == index:
                # if a character can be encoded in multiple alphabets, then it is impossible to decode
                if found:
                    return "Impossible to decode"
                    result_str += chr(ord('a') + num)
                    found = True

        if not found:
            return "Impossible to decode"

    return result_str