2015-02-10 694 views
0

我正在嘗試對Code Abbey執行parity control挑戰。我幾個月來一直有它的麻煩,但我終於有它... 差不多。它返回的輸出關閉了幾個字符,我想知道是否有人可以指向正確的方向。我很難過,部分是因爲我的代碼太瑣碎了,即使我不能真正解析它(我會解決這個問題)。奇偶校驗控制程序,Python

我希望這不是太靠近功課的幫助。我知道你們討厭那個。

import string 

characters = string.letters + ' ' + '.' + string.digits 

characters = zip(characters, [bin(ord(i))[2:] for i in characters]) 

nch = {} 

squareseven = 128 

for char in characters: 
    # For readability. a is the character, like A or ., b is the binary. 
    a = char[0] 
    b = char[1] 
    if b.count('1') % 2 != 0: 
     nch[a] = int(b, 2) + squareseven 
    else: 
     nch[a] = int(b, 2) 

with open('input.txt', 'r') as O: 
    O = map(int, str(O.read()).strip().split()) 

    decyphered = '' 

    for binary in O: 
     # If the number of ones is odd, 128 is added. 
     if bin(binary)[2:].count('1') % 2 != 0: 
      tmp = binary + squareseven 
     else: 
      tmp = binary 

     # Because the ASCII binaries only go up to 255. 
     if tmp < 256: 
      if tmp in nch.values(): 
       for char, b in nch.iteritems(): 
        if b == tmp: 
         decyphered += char 

with open('output.txt', 'w') as output: 
    output.write(decyphered) 
+0

它不是我們討厭的作業......它沒有表現出來的努力......乍一看這個問題並沒有受到這個問題的影響(它看起來像你給它一個非常誠實的動搖) – 2015-02-10 22:58:21

回答

1

大部分問題都可以將它們分爲更小的子問題

得到更好的攻擊

先寫一個方法來幫助檢查數據

def check_char(n): 
    """return ascii code if parity check success else None""" 
    bits = "{0:08b}".format(n) 
    if int(bits[0]) == sum(map(int,bits[1:]))%2: 
     return n&0x7f #get rid of the parity bit when return ascii 

然後一個方法來處理一行

def translate_line(line): 
    ascii_codes = map(int,line.split()) 
    checked_values = [check_char(n) for n in ascii_codes] 
    return "".join(chr(val) for val in checked_values if val) 


print translate_line("65 238 236 225 46") 

在你的線,然後只是路過循環它們