2

如何通过将消息中的每个字母替换为字母表中进一步的字母 k 位置来对其进行编码?例如,如果k=3,“a”被“d”替换,“b”被“e”替换,等等。字母环绕。“w”被“z”替换,“x”被“a”替换,“y”被“b”替换,“z”被“c”替换。您可以假设要编码的消息不是空的,只包含小写字母和空格。空格被编码为空格。这是我尝试过的,但它不像它需要的那样工作。我需要能够输入要跳过的字母数量。

def encode(string,keyletter):
  alpha="abcdefghijklmnopqrstuvwxyz"
  secret = ""
  for letter in string:
    index = alpha.find(letter)
    secret = secret+keyletter[index]
  print secret
4

2 回答 2

0

您可以利用 Python 的maketrans功能来生成合适的字符映射,如下所示:

import string

def encode(text, rotate_by):
    s_from = string.ascii_lowercase
    s_to = string.ascii_lowercase[rotate_by:] + \
           string.ascii_lowercase[:rotate_by]
    cypher_table = string.maketrans(s_from, s_to)
    return text.translate(cypher_table)

text = raw_input("Enter the text to encode: ").lower()
rotate_by = int(raw_input("Rotate by: "))
print encode(text, rotate_by)

这将显示:

Enter the text to encode: hello world
Rotate by: 3
khoor zruog
于 2015-10-02T13:31:05.823 回答
0

这是不需要重新排列字母字符串的简单版本。请注意,这不考虑错误的用户输入,例如输入单词而不是旋转数字。

while 1:
    rot = int(raw_input("Enter Rotation: "))
    cipher = raw_input("Enter String: ")
    secret,alpha = '', 'abcdefghijklmnopqrstuvwxyz'

    for i in cipher.lower():   #Loop through the original string 
        if i not in alpha:     #If the character in the original string is not in the alphabet just add it to the secret word
            secret += i
        else:
            x = alpha.index(i)   #Get index of letter in alphabet
            x = (x+rot)%26  #Find the index of the rotated letter
            secret += alpha[x]   #Add the new letter to the secret word
    print f

您可以将 for 循环中的所有内容压缩为一行,但这样读起来并不漂亮

f += i if i not in s else s[(s.index(i)+rot)%26]

如果您想对您的 Caesar Cipher 感兴趣,请查找一个键控 Caesar Cipher 并添加该选项。不过,这将需要操作您的 alpha 字符串。

于 2015-10-02T13:55:36.450 回答