2016-01-12 15 views
-2
def encrypt(text, key, direction): 
    if direction == 1: #The direction is either -1, or 1. If it is 1, it goes right. Otherwise, it will go left. 
     emptys='' 
     for x in text: 
      b = ord(x) #b is the individual characters after the ord() function 
      b+=key 
      if b<=122: 
       n = chr(b) #n is the converted letter of the encrypted ASCII number 
       emptys+=n 
      else: 
       o=b-90 
       q=chr(o) 
       emptys+=q 
     return emptys 
    else: 
     emptys='' 
     for x in text: 
      b = ord(x) #b is the individual characters after the ord() function 
      b=b-key 
      if b>=32: 
       n = chr(b) #n is the converted letter of the encrypted ASCII number 
       emptys+=n 
      else: 
       o=b+90 
       q=chr(o) 
       emptys+=q 
     return emptys 
+5

您应该格式化您的代码,而且:如果此代码没有问题,则它不属于Stack Overflow。为了改进**并假设此代码有效**,您可能想在[代码评论](http://codereview.stackexchange.com/)上尝试运气。 –

+0

您的代码太长,变量名太短,符号之间没有足够的空白。您应该能够通过重构仅使用一次的变量来将其降低到大约一半 –

回答

0

将您的代码书写愉快地将字母字符翻译为非字母字符,反之亦然(例如encrypt('abc', 25, 1)获得'z!"')。所以传统的凯撒密码的大多数定义是错误的,它应该只修改字母字符,并且应该在字母表中旋转它们。

也就是说,说得对,比你做得更容易。最好的方法是避免滚动你自己的轮换代码。 Python已经提供了一种非常好的方式来执行一对一的字符映射,str.translate。例如:

from string import ascii_letters, ascii_uppercase, ascii_lowercase 

def encrypt(text, key, direction): 
    # direction == -1 is trivially converted to direction == 1 case 
    if direction == -1: 
     key = 26 - key 

    # On Py2, you'd use the string module's string.maketrans instead of 
    # str.maketrans 
    trans = str.maketrans(ascii_letters, ascii_lowercase[key:] + ascii_lowercase[:key] + ascii_uppercase[key:] + ascii_uppercase[:key]) 

    return text.translate(trans)