目标是拥有一个我可以输入的程序,例如“ 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'
我一点都不明白。尝试重新排列代码时,我也遇到了其他各种语法错误。
您的代码有类型错误,因为您将getdigit
函数定义为将number
作为字符串,将n
作为整数,但是随后您又像getdigit(key, char)
这样调用了此函数,其中key
是字符串char
也是一个字符串-它是message
的一个字母,因为它来自for char in message
。
直接解决这个问题并不容易,因为n
参数应该是index,其中char
出现在message
中,但是您的代码无法访问该索引,并且您无法使用message.index(char)
方法来找到它,因为它给出了char
的first事件的索引,而不是current事件的索引。 enumerate
功能可用于访问列表理解中的索引。
就是说,以不需要索引的方式编写代码会容易得多。您可以使用enumerate
将zip
中的字母与message
中的相应数字配对,从而简化代码。这看起来像是一项家庭作业,所以我不会显示完整的解决方案,但是以下内容可能会给您一个有关如何做的想法:
key