凯撒密码蛮力成为一个功能

时间:2017-06-20 03:37:05

标签: python python-3.x

def caesar_decrypt(s,n):
    s1=""
    m = n % 26 if n > 26 else n
    for c in s:
        if c.isalpha():
          x = ord(c) - m
          if c.islower():
             c = chr(x + 26) if x < ord('a') else chr(x)
          elif c.isupper():
             c = chr(x + 26) if x < ord('A') else chr(x)
        s1 += c
    return s1

def brute_force_decrypt(ciphertext):
    for i in range(1,27):
        d=caesar_decrypt(ciphertext,i)
        print (i,d)
brute_force_decrypt(open('text.txt').read())

因此,我的代码做得很好,但我希望将代码放入一个名为brute_force_decrypt(ciphertext)的函数中。我不确定如何结合我的两个功能。我需要一些帮助。

2 个答案:

答案 0 :(得分:2)

不要,如果一个函数做了一件事并且命名良好,那么函数是最好的。

而是创建另一个调用这些函数的函数。

函数中的越少越容易理解,错误的可能性就越小。

答案 1 :(得分:1)

您可以在caesar_decrypt(s,n)

中加入brute_force_decrypt(ciphertext)的代码
def brute_force_decrypt(ciphertext):
    for n in range(1,27):
        s1=""
        m = n % 26 if n > 26 else n
        for c in ciphertext:
            if c.isalpha():
              x = ord(c) - m
              if c.islower():
                 c = chr(x + 26) if x < ord('a') else chr(x)
              elif c.isupper():
                 c = chr(x + 26) if x < ord('A') else chr(x)
            s1 += c
        d = s1
        print (n,d)
brute_force_decrypt(open('text.txt').read())

(请注意变量i更改为n