Уже всю голову сломал, но никак не могу понять, в чем проблема декодирования. Условия задачи (напишу в оригинале, потому как вдруг что-то перевел не так, и от этого утерялась какая нибудь деталь):
Suppose we know the process by which a string s
was encoded to a string r
(see explanation below). The aim of the kata is to decode this string r
to get back the original string s
.
Explanation of the encoding process:
input: a string
s
composed of lowercase letters from"a"
to"z"
, and a positive integernum
we know there is a correspondence between
abcde...uvwxyz
and0, 1, 2 ..., 23, 24, 25
:0 <-> a, 1 <-> b ...
if
c
is a character ofs
whose corresponding number isx
, apply tox
the functionf: x-> f(x) = num * x % 26
, then findch
the corresponding character off(x)
Accumulate all these
ch
in a stringr
concatenate
num
andr
and return the result
For example:
encode("mer", 6015) --> "6015ekx"
m --> 12, 12 * 6015 % 26 = 4, 4 --> e
e --> 4, 4 * 6015 % 26 = 10, 10 --> k
r --> 17, 17 * 6015 % 26 = 23, 23 --> x
So we get "ekx", hence the output is "6015ekx"
Task
A string s
was encoded to string r
by the above process. complete the function to get back s
whenever it is possible.
Indeed it can happen that the decoding is impossible for strings composed of whatever letters from "a" to "z" when positive integer num has not been correctly chosen. In that case return "Impossible to decode"
.
Examples
decode "6015ekx" -> "mer"
decode "5057aan" -> "Impossible to decode"
Функцию декодирования я осилил, а вот предусмотреть то, что на вход будут подаваться неверные данные, пока не смог, потому что я в принципе не могу понять, что есть неверные данные
и почему они считаются таковыми.
Функция декодирования:
def decode(r):
num = int(''.join(map(str, [x for x in r if x.isdigit()]))) # отделяем число от кодированных символов
res = ''
for x in r[len(str(num)):]: # цикл по строке без цифр
res += chr({x * num % 26: x for x in range(26)}[ord(x)-97]+97) # добавляю декодированный символ в результат
return res
PS: Все тесты с корректными данными проходит успешно.
ca
n
было задано константой, я упустил что здесьn
задаётся во входных данных.