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

时间:2020-01-26 19:31:55

标签: python caesar-cipher

目标是拥有一个我可以输入的程序,例如“ 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'

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

1 个答案:

答案 0 :(得分:0)

您的代码有类型错误,因为您将getdigit函数定义为将number作为字符串,将n作为整数,但是随后您像{{1 }},其中getdigit(key, char)是一个字符串,key也是一个字符串-它是char的一个字母,因为它来自message

直接解决此问题并不容易,因为for char in message应该是 index ,其中n出现在char中,但是您的代码却没有无法知道索引,因此无法使用message方法来找到它,因为它给出了message.index(char) first 出现的索引,而不是< em>当前发生。 enumerate函数可用于访问列表理解中的索引。

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

key