gpt4 book ai didi

python - 奇偶校验控制程序,Python

转载 作者:行者123 更新时间:2023-12-01 04:51:10 27 4
gpt4 key购买 nike

我正在尝试执行parity control Code Abbey 的挑战。几个月来我一直遇到这个问题,但我终于解决了......几乎。它返回的输出有几个字符,我想知道是否有人可以指出我正确的方向。我很困惑,部分原因是我的代码太草率了,甚至我无法真正解析它(我会解决这个问题)。

我希望这不会太接近家庭作业帮助。我知道你们讨厌这样。

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)

最佳答案

大多数问题可以通过将其分解为更小的子问题来更好地解决

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

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")

然后只需循环传递它们即可

关于python - 奇偶校验控制程序,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443493/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com