奇偶校验控制程序

2024-09-14 23:07:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对代码修道院进行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)

Tags: theinforoutputstringifistmp
1条回答
网友
1楼 · 发布于 2024-09-14 23:07:08

将大多数问题分解成更小的子问题,可以更好地解决这些问题

首先编写一个方法来帮助检查数据

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

然后是一个处理单行的方法

^{pr2}$

然后把你的线绕过去

相关问题 更多 >