Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按不同值移动每个字母的凯撒密码?_Python_Caesar Cipher - Fatal编程技术网

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

Python 按不同值移动每个字母的凯撒密码?,python,caesar-cipher,Python,Caesar Cipher,目标是有一个我可以输入的程序,例如“helloworld”和“0123456789”,并接收“hfnosbuytm”作为输出。与常规的凯撒密码不同,它每字符只能移动0到9个字母。字符串和键都是相同的长度,所以我知道我需要使用相同的长度值并在for循环中移动它们,但是我在语法方面遇到了问题。以下是我最终得到的结果: def getdigit(number, n): return int(number) // 10**n % 10 message = "helloworld" key =

目标是有一个我可以输入的程序,例如“helloworld”和“0123456789”,并接收“hfnosbuytm”作为输出。与常规的凯撒密码不同,它每字符只能移动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'
回溯(最近一次呼叫最后一次):
文件“c:\users\ants\mu\u code\blank.py”,第7行,在
encoded=“”.join([alphabet[(alphabet.find(char)+getdigit(key,char))%26]表示消息中的字符])
文件“c:\users\ants\mu\u code\blank.py”,第7行,在
encoded=“”.join([alphabet[(alphabet.find(char)+getdigit(key,char))%26]表示消息中的字符])
文件“c:\users\ants\mu\u code\blank.py”,第2行,在getdigit中
返回int(number)//10**n%10
TypeError:不支持**或pow()的操作数类型:“int”和“str”

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

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

要直接解决这个问题并不简单,因为
n
应该是
char
出现在
message
中的索引,但是您的代码不知道索引,并且您不能使用
message.index(char)
方法来查找它,因为它给出了第一次出现的
char
的索引,不是当前事件的索引。该函数可用于访问列表中的索引

也就是说,以不需要索引的方式编写代码会简单得多。您可以使用将
消息
中的字母与
中相应的数字配对,从而简化代码。这看起来像是一项家庭作业,因此我不会给出完整的解决方案,但以下内容可能会让您了解如何做:

>message=“helloworld”
>>>key=“0123456789”
>>>对于字符,zip中的数字(消息,键):
...     打印('字符:',字符,'数字:',数字)
... 
字符:h数字:0
字符:e数字:1
字符:l数字:2
字符:l数字:3
字符:o数字:4
字符:w位:5
字符:o数字:6
字符:r数字:7
字符:l数字:8
字符:d数字:9
TypeError:不支持**或pow()的操作数类型:'int'和'str'这很简单,我相信您可以做到!它说错误与
**
中的值类型有关:这两个值是
10
n
,我让您猜哪一个有问题;)这被称为密码,除非您将自己限制为每个字母最多移位9。