2014-02-19 42 views
1

太多的无奈之后,我做了我的第一个凯撒解码器:)如何在Python(2.7)中制作凯撒解码器循环?

但是现在的问题是,使程序循环...

例如,如果我们想转变doge 1,无问题,这是ephf ...

xyz,而转移是4?

所以编程专业人员帮助第一次新手又名福利局了:P 谢谢...

import string 
def main():   
    inString = raw_input("Please enter the word to be " 
         "translated: ") 
    key = int(raw_input("What is the key value? ")) 

    toConv = [ord(i) for i in inString] #now want to shift it by key 
    toConv = [x+key for x in toConv] 
    #^can use map(lambda x:x+key, toConv) 
    result = ''.join(chr(i) for i in toConv) 

    print "This is the final result due to the shift", result 
+0

相关:http://codereview.stackexchange.com/questions/32694/python-caesars-cipher-how-could-i-do-it-better/32696#32696 – kojiro

回答

0

只需添加key所有实际的字符代码,然后如果添加的值大于z更大,以字符代码z为模,并加上字符代码a

inString, key = "xyz", 4 
toConv = [(ord(i) + key) for i in inString] #now want to shift it by key 
toConv = [(x % ord("z")) + ord("a") if x > ord("z") else x for x in toConv] 
result = ''.join(chr(i) for i in toConv) 
print result # cde 
0

在一般情况下,实现所谓的“包装”您使用要换行的数量,你希望它在包装的范围内模函数(%在Python)。例如,如果我想通过10打印数字1 bajillion次,我会做:

i = 0 
while 1: 
    print(i%10+1) 
    # I want to see 1-10, and i=10 will give me 0 (10%10==0), so i%10+1! 
    i += 1 

在这种情况下,它是一个有点困难,因为你使用ord,不具有价值的一个很好的幸福“范围” 。如果你做了类似string.ascii_lowercase你可以做...

import string 
codex = string.ascii_lowercase 

inString = "abcdxyz" 
key = 3 
outString = [codex[(codex.index(char)+key)%len(codex)] for char in inString] 

不过既然你使用ord,我们有种从ord('A') == 65ord('z')==122,等等一系列的0 - > 57(例如range(58)与65恒定换句话说:

codex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz" 
# every char for chr(65) -> chr(122) 

codex = ''.join([chr(i+65) for i in range(58)]) # this is the same thing! 

,我们可以做到这一点,而不是,但它会包含字符[\]^_`

inString, key = 'abcxyzABCXYZ', 4 
toConv = [(ord(i)+key-65)%58 for i in inString] 
result = ''.join(chr(i+65) for i in toConv) 
print(result) 
# "efgBCDEFG\\]^" 
0

我推荐使用string.translate()

因此,我们可以做到以下几点:

key = 1 
table = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[key:] + string.ascii_lowercase[:key] + string.ascii_uppercase[key:] + string.ascii_uppercase[:key]) 

,然后我们可以使用它,如下所示:

'doge'.translate(table) # Outputs 'ephf' 
'Doge'.translate(table) # Outputs 'Ephf' 
'xyz'.translate(table) # Outputs 'yza' 

特别是,这并没有改变未ASCII小写字符或大写字母,如数字或空格。

'3 2 1 a'.translate(table) # Outputs '3 2 1 b' 
0

这是我写的Python代码,很容易理解。另外,我认为经典凯撒密码没有定义如何处理标点符号;我认为这些经典的秘密信息是不准确的,只能包含字母。我写这只是为了处理经典的罗马字母,并且不改变任何其他字符。

作为一个奖励,你可以使用这个代码13的位移来解码ROT13编码的笑话。

def caesar_ch(ch, shift): 
    """ 
    Caesar cipher for one character. Only shifts 'a' through 'z' 
    and 'A' through 'Z'; leaves other chars unchanged. 
    """ 
    n = ord(ch) 
    if ord('a') <= n <= ord('z'): 
     n = n - ord('a') 
     n = (n + shift) % 26 
     n = n + ord('a') 
     return chr(n) 
    elif ord('A') <= n <= ord('Z'): 
     n = n - ord('A') 
     n = (n + shift) % 26 
     n = n + ord('A') 
     return chr(n) 
    else: 
     return ch 

def caesar(s, shift): 
    """ 
    Caesar cipher for a string. Only shifts 'a' through 'z' 
    and 'A' through 'Z'; leaves other chars unchanged. 
    """ 
    return ''.join(caesar_ch(ch, shift) for ch in s) 

if __name__ == "__main__": 
    assert caesar("doge", 1) == "ephf" 

    assert caesar("xyz", 4) == "bcd" 

    assert caesar("Veni, vidi, vici.", 13) == "Irav, ivqv, ivpv." 

最后部分是代码的“自检”。如果您将其作为独立程序运行,它将自行测试,并在测试失败时“断言”。

如果您对此代码有任何疑问,只需询问,我会解释。

0

我知道这是一个古老的话题,但我恰好在今天正在努力。我发现这个线程中的答案很有用,但他们似乎都使用循环决定。我想通过使用模数(余数)运算符(%)来实现同样的目标。这允许号码保持在表格的范围内并循环。它也允许轻松解码。

# advCeaser.py 
# This program uses a ceaser cypher to encode and decode messages 
import string 

def main(): 
    # Create a table to reference all upper, lower case, numbers and common punctuation. 
    table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890,[email protected]' 

    print 'This program accepts a message and a key to encode the message.' 
    print 'If the encoded message is entered with the negative value of the key' 
    print 'The message will be decoded!' 

    # Create accumulator to collect coded message 
code ='' 

    # Get input from user: Message and encode key 
    message = raw_input('Enter the message you would like to have encoded:') 
    key = input('Enter the encode or decode key: ') 

    # Loop through each character in the message 
    for ch in message: 
     # Find the index of the char in the table add the key value 
     # Then use the remainder function to stay within range of the table. 
     index = ((table.find(ch)+key)%len(table)) 

     # Add a new character to the code using the index 
     code = code + table[index] 

    # Print out the final code 
    print code 

main() 

编码和解码输出看起来像这样。

编码:

This program accepts a message and a key to encode the message. 
If the encoded message is entered with the negative value of the key 
The message will be decoded! 
Enter the message you would like to have encoded:The zephyr blows from the east to the west! 
Enter the encode or decode key: 10 
croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G 

解码:

This program accepts a message and a key to encode the message. 
If the encoded message is entered with the negative value of the key 
The message will be decoded! 
Enter the message you would like to have encoded:croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G 
Enter the encode or decode key: -10 
The zephyr blows from the east to the west! 

很抱歉,如果我的格式看起来很catywompus我硬是找到计算器昨天!是的,我的字面意思是字面意思:)