我正在尝试对Code Abbey进行parity control挑战。几个月来我一直遇到麻烦,但我终于有了...... 几乎。它返回的输出是几个字符,我想知道是否有人能指出我正确的方向。我很难过,部分原因是因为我的代码太乱了,即使我无法解析它(我会解决它)。
我希望这不太接近家庭作业的帮助。我知道你们讨厌那个。
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 :(得分:2)
通过将问题分解为更小的子问题,可以更好地攻击大多数问题
首先编写一个方法来帮助检查数据
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")
然后循环遍历你的行