在 Python 中反转此编码算法

reversing this encoding algorithm in Python

我需要帮助将此编码算法转换为解码算法。我了解交换功能,但我在处理其余代码时遇到问题。

from string import ascii_letters, digits


def shift(text, shift: int = 0):
    SPACE = ' '
    letters = ascii_letters + digits + SPACE
    letters_length = len(letters)

    shifted_chars = []
    for char in text:
        if char in letters: 
            shifted_chars.append(letters[(letters.index(char) + shift) % letters_length])
        else:
            shifted_chars.append(char)
    return ''.join(shifted_chars)


def swap(text):
    middle = len(text) // 2
    return text[middle:] + text[:middle]

def encode(text):
    if len(text) < 2:
        return shift(text, 7)

    for i in range(31):
        text = swap(shift(text, i))

    return text

由于 Parisa.H.R 的有用评论已修复。

deswap(text) 函数在奇数 len(text) 的情况下均衡 swap(text) 的不对称结果。

from string import ascii_letters, digits


def shift(text, shift: int = 0):
    SPACE = ' '
    letters = ascii_letters + digits + SPACE
    letters_length = len(letters)
    shifted_chars = []
    for char in text:
        if char in letters: 
            shifted_chars.append(letters[(letters.index(char) + shift) % letters_length])
        else:
            shifted_chars.append(char)
    return ''.join(shifted_chars)


def swap(text):
    middle = len(text) // 2
    return text[middle:] + text[:middle]


def deswap(text):
    middle =  (len(text) + (len(text) % 2)) // 2
    return text[middle:] + text[:middle]


def encode(text):
    if len(text) < 2:
        return shift(text, 7)
    for i in range(31):
        text = swap(shift(text, i))
    return text


def decode(text):
    if len(text) < 2:
        return shift(text, -7)
    for i in range(30, -1, -1):
        text = deswap(shift(text, -i))
        # text = shift(deswap(text), -i)
    return text

输出:

decode(encode('opening'))   
# 'opening'
decode(encode('openin'))
# 'openin'
decode(encode('Quora'))
# 'Quora'
decode(encode('Quoran'))
# 'Quoran'
decode(encode(ascii_letters + digits)) == ascii_letters + digits
# True
decode(encode(ascii_letters + digits + ' ')) == ascii_letters + digits + ' '
# True