将增量计算过多。输入打印次数过多。python

2024-05-05 00:07:10 发布

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

def key(shift):
    data = []
    string = input("Please enter the string you wish to decode.\n")
    for i in string:
        if i.strip() and i in ALPHABET:
            data.append(ALPHABET[(ALPHABET.index(i) - shift) % 26])
        else:
            data.append(i)
    output = ''.join(data)
    return output

def run():

    data = []
    count = 0
    shift = 0
    for shift in range (26):
        count +=1
        if key(shift) == "hello world":
            print("Decoded.")
        else:
            print("Not this time!")
        print(count)
        print(key(shift))

当我运行我的程序时,它应该在计数3处执行“解码”,因为将khoor zruog解码到hello world需要3个班次。此外,输入“请输入您希望解码的字符串”应该打印一次,而不是打印很多次

Please enter the string you wish to decode.
khoor zruog
Not this time!
1
Please enter the string you wish to decode.
khoor zruog
khoor zruog
Please enter the string you wish to decode.
khoor zruog
Not this time!
2
Please enter the string you wish to decode.
khoor zruog
jgnnq yqtnf
Please enter the string you wish to decode.
khoor zruog
Not this time!
3
Please enter the string you wish to decode.
khoor zruog
ifmmp xpsme
Please enter the string you wish to decode.
khoor zruog
Decoded.
4
Please enter the string you wish to decode.
khoor zruog
hello world
Please enter the string you wish to decode.

这就是我试图执行代码时发生的情况。我不知道为什么它会递增到0,也不知道为什么它会多次询问我输入。有人能帮我吗

编辑:

def key(shift,string):
    data = []
    for i in string:
        if i.strip() and i in ALPHABET:
            data.append(ALPHABET[(ALPHABET.index(i) - shift) % 26])
        else:
            data.append(i)
    output = ''.join(data)
    return output

def run():
    data = []
    string = input("Please enter the string you wish to decode.\n")
    plaintext = input("Please enter plaintext word.\n")
    count = 0
    shift = 1
    for shift in range (26):
        count +=1
        if plaintext in key(shift,string):
            print(key(shift,string))
            print("The key is: ", count)
            print("Decoded.")
            break
        else:
            print(key(shift,string))
            print("Not this time!")
        print(count)

Tags: thetokeyinyoudatastringshift
1条回答
网友
1楼 · 发布于 2024-05-05 00:07:10

你的绳子

string = input("Please enter the string you wish to decode.\n")

在for循环内调用的函数内。这就是为什么您会多次收到打印对账单

删除该输入语句,您的解码问题将得到解决

相关问题 更多 >