使用Python Caesar代码 - 需要帮助了解前几行代码

时间:2014-11-16 13:13:25

标签: python loops encryption decode encode

我在python中创建了一个Caesar密码程序,它对消息进行编码,解码,读取和写入。我的解决方案完全正常,我没有遇到任何问题。我的目标是尽可能用尽可能少的代码完成任务,经过大量研究,我使用了一些代码来获取灵感。我尝试了很多不同的版本,但这似乎对我来说效果最好。

我要问的是,我想了解代码的前5条基本行是如何工作的,在这几行代码中,具体数字的重要性,循环和函数。我只想要几句话来解释这5行代码负责的进程或计算以及它们如何执行它们。

任何帮助都会受到很大的欢迎,因为我一直在研究类似的代码集,并且无法在我的写作中找到代码的任何解释。很抱歉有冗长的背景信息。

以下是我的全部代码:

def caesar(s, k, decode = False):
  if decode: k = 26 - k
  return "".join([chr((ord(i) - 65 + k) % 26 + 65)
                for i in s.upper()
                if ord(i) >= 65 and ord(i) <= 90 ])
result = str
decrypt = str
offset = int
exit = False
while(exit == False):
  print " "
  print " " 
  print "Welcome to Caeser's Cipher code, you can encrypt, decrypt, read, and store messages"
  print "DECRYPT - DECRYPT A MESSAGE"
  print "ENCRYPT - ENCRYPT A MESSAGE"
  print "READ - READ AND DECODE A MESSAGE"
  print "EXIT - EXIT THE PROGRAM"

  NoOfLetters = 26
  offset = 0
  option = raw_input("Please Enter your choice: ")

  if(option == "DECODE"):
    decrypt = raw_input("Enter the coded message: ")
    offset = int(raw_input("Enter the  Offset as an integer: "))
    print "Result: "
    print caesar(decrypt, offset, decode = True)
    print

  elif(option == "ENCODE"):
    encrypt = raw_input("Enter the message to code")
    offset = int(raw_input("Enter the Offset as integer: "))d
    print "Result: "
    print caesar(encrypt, offset, decode = False)
    result = caesar(encrypt, offset, decode = False)

    option2 = raw_input("Would you like to store this coded message and offset? (Y/N): ")
    if(option2 == "Y"):
      f = open("code.txt", "w")
      print >> f, result
      print >> f, offset
      f.close()
      print"The message and offset has been stored in a file called 'code.txt'"

  elif(option == "READ"):
    print"The program is reading and decrypting the code stored in 'code.txt'"
    print"The code.txt file is stored in the same location as the application"
    f = open("/Users/Emaad/Desktop/CIPHER CODE/code.txt")
    decrypt = f.readline()
    offset = int(f.readline())
    f.close()
    print "Result:"
    print caesar(decrypt, offset, decode = True)
    print "Offset:"
    print offset


  elif(option == "EXIT"):
    print"Thanks for using..."
    print"exiting the application...."
    exit = True

以下是我想了解的代码行:

def caesar(s, k, decode = False):
    if decode: k = 26 - k
    return "".join([chr((ord(i) - 65 + k) % 26 + 65)
                for i in s.upper()
                if ord(i) >= 65 and ord(i) <= 90 ])

1 个答案:

答案 0 :(得分:2)

有助于理解我们是否将代码拆分为更小的函数:

def chr2int(i):
    return ord(i) - 65

这是用于将大写字母映射到从0开始的整数。示例:

chr2int('A') == ord('A') - 65 == 0
chr2int('B') == ord('B') - 65 == 1
chr2int('Z') == ord('Z') - 65 == 25

65是大写字母&#39; A&#39;

的十进制代码
ord('A') == 65

rot()将k添加到数字n(模26):

def rot(n, k):
    return (n + k) % 26

26是从A到Z的所有字母的数量:

ord('Z') - ord('A') + 1 == 26 

示例:

rot(1, 1) == 2
rot(25, 0) == 25
rot(25, 1) == 0
rot(25, 2) == 1

int2chr()执行chr2int的反函数 - 将整数转换回字母。

def int2chr(i):
    return chr(i + 65)

现在,您可以将三个函数组合在一个(大写)字符中执行Caeser chiper:

def caeser_char(char, key):
    return int2chr(rot(chr2int(char), key))

要将ceaser chiper应用于整个单词,您可以使用列表推导:

def ceaser(word, key):
    chars = [caeser_char(i, key)                # perform caeser cipher
             for i in word.upper()              # for each char in word
             if ord(i) >= 65 and ord(i) <= 90]  # only if i is a letter
                                                # (between word('A')==65 and ord('Z')==90)
    return "".join(chars)                       # build a word from a list of chars

要解码单词,您只需要找到函数给出的反向键:

def decode_key(encode_key):
    return 26 - encode_key

希望这有帮助。