Cipher/Decipher Python 初学者计划

Cipher/Decipher Python Beginner Program

问题:有人可以编辑我的 2 行代码吗?

只是想指出这是针对学校作业的,所以我不想 post 我的所有代码都用来防止 copy/plagiarism 问题。由于我只是对作业的一小部分要求有困难,所以我不认为我的所有代码都是必需的。

我指的是 assgn 的要求:

Newx=ord(x)+3
Newx will be an integer. To find out what letter that integer represents you can use the chr function as in: actualLetter = chr(x) Write a function named cipher that takes a string and a key (integer). The function ciphers the string into another string and returns the new string. Note that when we reach 'z', and we want to add the key, we must 'roll' into the alphabet one more time, hence ord('z')+3 should give us ord('c').

当我 运行 测试我的程序并输入 'z' 时,我没有得到 'c',我得到:

导致此问题的这部分程序的代码是:

example_string = letters[((ord(i)+key)%97)%26]
example2_string += letters[((ord(i)-key)%97)%26]

(example_string 和 example2_string 是假名)

我认为模数 97 在错误的位置。你应该做 ord(i)%97-3 然后它工作。

chr(ord('a')+(ord('z')%97-3)%26)
example_string = letters[((ord(i)%97+key)%26]

您可以做的另一件事是从 z 中减去 a,然后像这样进行减法:

chr(ord('a')+(ord('z')-ord('a')-3)%26)

您不应执行任何对 97 取模的操作。仅当您的字母表包含 97 个字符时才执行对 97 取模的操作。

正确的做法是:

  1. 判断字符是否为字母;
  2. 将字母转换为0到字母表大小之间的数字(常见的ABC当然是26个字符大小);
  3. 添加或减去键值,对字母表的大小取模(对于此类操作,您可以简单地先添加/减去,然后执行取模);
  4. 再次将结果数字转换为字母,这就是你的密文。

所以你会得到:

alphabetSize = ord('z') - ord('a') + 1

k = 3
c = 'z'

if (ord(c) >= ord('a')) | (ord(c) <= ord('z')):
    n = ord(c) - ord('a')
    n = (n + k) % alphabetSize
    ctc = chr(n + ord('a'))
else:
    ctc = c

print ctc

魔法(在本例中是因为 + 在密钥 k 之前使用的加密)当然在 if 语句的 3 行中。当然可以将它们组合起来——如果需要的话,可以合并成一行——但这更简洁。