为什么解密程序中的间距不正确?

2024-09-28 19:27:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我创造了一个破译器

code = input("What text would you like to decipher: ")
number_of_gos = 0
code_listed = []
string = ""

def change_string():
    global string
    code_listed.append(string)
    string = ""
    return string

for n in code:
    if n == " ":
        pass
    else:
        if number_of_gos % 4 == 0 and number_of_gos > 0:
            string = change_string()
        string += n
        number_of_gos += 1

code_listed.append(string)

chars = {
    "uytv": "a",
    "ghas": "b",
    "opts": "c",
    "qwra": "d",
    "bcvb": "e",
    "wdrs": "f",
    "rwes": "g",
    "teya": "h",
    "uisd": "i",
    "hgnl": "j",
    "mvbn": "k",
    "onhm": "l",
    "ponu": "o",
    "gbho": "m",
    "wesg": "n",
    "idgf": "p",
    "asfb": "q",
    "nbnf": "r",
    "dngd": "s",
    "nbvd": "t",
    "mbnf": "u",
    "ignf": "v",
    "fddf": "w",
    "sabd": "x",
    "asda": "y",
    "qfjy": "z"
}

new_code = ""
for char in code_listed:
    new_char = chars[char]
    new_code += new_char

for char in code:
    if char == " ":
        code = list(code)
        char_index = code.index(char)
        new_code = list(new_code)
        new_code.insert(int(char_index/4 + 1), char)
        newer_code = ""
        code.pop(char_index)
        for char_awesome in new_code:
            newer_code += char_awesome

try:
    print(newer_code)
except NameError:
    print(new_code)

输入teyabcvbonhmonhmponu nbvdteyabcvbnbnfbcvb返回hellot here。我不知道为什么会发生这种情况,因为我的密码用空格给出了正确的输出,但是破译是不可靠的,我试着通过原始输入,将其列成一个列表,然后如果字符是一个空格,我会得到它的索引,将其除以四,从原始代码中删除,然后将其添加到一个新字符串中,但结果是不可靠的。有人能帮忙吗


Tags: ofinnumbernewforstringindexif
2条回答

Brad提供了一个直接的解决方案。下面是一个较短的解决方案:

chars = {....}
code = input("What text would you like to decipher: ")
result = " ".join(["".join(chars["".join(j)] for j in zip(*[iter(i)]*4)]) for i in code.split())
print(result)

有用的链接:How does zip(*[iter(s)]*n) work in Python?

嗯,调试有点困难,因为代码很混乱,但这里我有一个更简单的解决方案,我不知道它是否适合您。无论如何,我会在下面告诉你,每一行的解释都在那里,如果你有疑问,请告诉我:)

code = input("What text would you like to decipher: ")
words = code.split(' ') # If there's any space
string_result = ''
chars = {
    "uytv": "a",
    "ghas": "b",
    "opts": "c",
    "qwra": "d",
    "bcvb": "e",
    "wdrs": "f",
    "rwes": "g",
    "teya": "h",
    "uisd": "i",
    "hgnl": "j",
    "mvbn": "k",
    "onhm": "l",
    "ponu": "o",
    "gbho": "m",
    "wesg": "n",
    "idgf": "p",
    "asfb": "q",
    "nbnf": "r",
    "dngd": "s",
    "nbvd": "t",
    "mbnf": "u",
    "ignf": "v",
    "fddf": "w",
    "sabd": "x",
    "asda": "y",
    "qfjy": "z"
}
for word in words:
    out = [(word[i:i+4]) for i in range(0, len(word), 4)] # Split the word into 4 characters
    result = [chars[a] for a in out] # Getting the representation
    string_result += ''.join(result) + ' ' # Adding the space in each iteration

print(string_result) # Outputs "hello there"

相关问题 更多 >