2015-02-10 92 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") 

在你的线,然后只是路过循环它们