将每个字母移动不同值的凯撒密码?

问题描述 投票:0回答:1

目标是拥有一个我可以输入的程序,例如“ helloworld”和“ 0123456789”,并接收“ hfnosbuytm”作为输出。与常规的Caesar密码不同,它仅意味着每个字符移动0到9个字母。字符串和键都具有相同的长度,因此我了解到我需要使用相同的长度值并将它们移至for循环中,但是语法上遇到了麻烦。这就是我最终得到的:

def getdigit(number, n):
    return int(number) // 10**n % 10

message = "helloworld"
key = "0123456789"
alphabet = "abcdefghijklmnopqrstuvwxyz"
encoded = "".join([alphabet[(alphabet.find(char)+getdigit(key, char))%26] for char in message])
print(encoded)

但是它给出了错误:

Traceback (most recent call last):
  File "c:\users\ants\mu_code\blank.py", line 7, in <module>
    encoded = "".join([alphabet[(alphabet.find(char)+getdigit(key, char))%26] for char in message])
  File "c:\users\ants\mu_code\blank.py", line 7, in <listcomp>
    encoded = "".join([alphabet[(alphabet.find(char)+getdigit(key, char))%26] for char in message])
  File "c:\users\ants\mu_code\blank.py", line 2, in getdigit
    return int(number) // 10**n % 10
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'

我一点都不明白。尝试重新排列代码时,我也遇到了其他各种语法错误。

python caesar-cipher
1个回答
0
投票

您的代码有类型错误,因为您将getdigit函数定义为将number作为字符串,将n作为整数,但是随后您又像getdigit(key, char)这样调用了此函数,其中key是字符串char也是一个字符串-它是message的一个字母,因为它来自for char in message

直接解决这个问题并不容易,因为n参数应该是index,其中char出现在message中,但是您的代码无法访问该索引,并且您无法使用message.index(char)方法来找到它,因为它给出了charfirst事件的索引,而不是current事件的索引。 enumerate功能可用于访问列表理解中的索引。

就是说,以不需要索引的方式编写代码会容易得多。您可以使用enumeratezip中的字母与message中的相应数字配对,从而简化代码。这看起来像是一项家庭作业,所以我不会显示完整的解决方案,但是以下内容可能会给您一个有关如何做的想法:

key
© www.soinside.com 2019 - 2024. All rights reserved.