2013-10-28 133 views
0

我想写我自己的python代码来强制恺撒密码,我需要一些帮助。我在函数的代码末尾附近特别需要帮助。我想知道如何专门打印,以便在每次尝试之后都有差距。我正在使用python 3.3,并在3周前刚开始编码。凯撒密码蛮力解密

print ("The plaintext will be stripped of any formatting such as spaces.") 
freqlist = [] 
maxkey = 26 
if key > maxkey: 
    raise Exception("Enter a key between 0 and 26: ") 
elif key < 0: 
    raise Exception("Enter a key between 0 and 26: ") 
freq = [] 
inpt=input("Please enter the cipher text:") 
inpt = inpt.upper() 
inpt = inpt.replace(" ", "") 
inpt = inpt.replace(",", "") 
inpt = inpt.replace(".", "") 
for i in range(0,27): 
     key = i 

def decrypt(): 
    for i in range(0,27): 
     for a in inpt: 
      b=ord(a) 
      b-= i 
      if b > ord("Z"): 
       b -= 26 
      elif b < ord("A"): 
       b+=26 
      freqlist.append(b) 
     for a in freqlist: 
      d=chr(a) 
      freq.append(d) 
      freq="".join(freq) 
      print(freq.lower(),"\n") 
decrypt() 

我想使用for循环,我不认为它真的有效。

+2

对不起一些解释,以“有效合作”你的意思是完全不工作(如果是这样,与什么错误信息)或只是没有效率?这可能是一个语言问题,但我不明白。 – Jblasco

+0

所以现在你有一个每个凯撒密码的输入频率表。你打算如何处理这些表格?你将如何确定哪个密码是正确的? – 2013-10-28 15:20:41

+0

我只需要帮助和建议如何改善此代码。 – iabestever

回答

1

根据您发布的错误,我认为这应该有所帮助。

在Python中,您可以拥有同名的本地和全局变量。该函数中的freq是本地的,因此全局freq的初始化不会触及本地。要使用全球freq,您必须通过global statement告知该功能。这在Python FAQs中有更多解释。

这应该足以让你回到正轨。

编辑: 下面是你decrypt功能的编辑,与变化

def decrypt(): 

    # we don't need the zero start value, that's the default 
    # test all possible shifts 
    for i in range(27): 

     # initialize the array 
     freqlist = [] 

     # shift all the letters in the input 
     for a in inpt: 
      b = ord(a) 
      b -= i 
      if b > ord("Z"): 
       b -= 26 
      elif b < ord("A"): 
       b+=26 
      freqlist.append(b) 

     # now put the shifted letters back together 
     shifted = "" 
     for a in freqlist: 
      d = chr(a) 
      # append the shifted letter onto our output 
      shifted += d 

     # after we put the decrypted string back together, print it 
     # note this is outside the letter loops, 
     # but still inside the possible shifts loop 
     # thus printing all possible shifts for the given message 
     print(d) 
+0

谢谢。这帮助了我,但我也在寻找更多的东西,这也会帮助我展示我的成果。 – iabestever