这道题我回答过的,不知道怎么被删除了。下面是上次回答的代码。
import?randomcnt_n?=?int(input("题目数量:"))
max_n?=?int(input("最大数字:"))
#?产生乘法查找表
times_list?=?[]
for?i?in?range(max_n):
??for?j?in?range(max_n):
????if?i?*?j?<=?max_n:
??????qst?=?str(i)?+?"*"?+?str(j)
??????rst?=?str(i*j)
??????if?qst?not?in?times_list:
????????times_list.append([qst,?rst])
#?题目表
question_list?=?[]
for?_?in?range(cnt_n):
??#?随机运算,0+,1-,2*,3/
??op?=?random.randint(0,?3)
??#?+
??if?op?==?0:
????x1?=?random.randint(0,?max_n)
????x2?=?random.randint(0,?max_n?-?x1)
????result?=?x1?+?x2
????qst?=?str(x1)?+?"+"?+?str(x2)?+?"="
????question_list.append([qst,?result])
??#?-
??elif?op?==?1:
????x1?=?random.randint(0,?max_n)
????x2?=?random.randint(0,?x1)
????result?=?x1?-?x2
????qst?=?str(x1)?+?"-"?+?str(x2)?+?"="
????question_list.append([qst,?result])
??#?*
??elif?op?==?2:
????tmp?=?random.sample(times_list,?1)
????qst?=?tmp[0][0]?+?"="
????question_list.append([qst,?tmp[0][1]])
??#?/
??elif?op?==?3:
????tmp?=?random.sample(times_list,?1)
????x1,?x2?=?tmp[0][0].split("*")
????result?=?tmp[0][1]
????while?int(x1)?==?0:
??????tmp?=?random.sample(times_list,?1)
??????x1,?x2?=?tmp[0][0].split("*")
??????result?=?tmp[0][1]
????qst?=?result?+?"/"?+?x1?+?"="
????question_list.append([qst,?x2])
print("开始回答:")
wrong?=?""
for?i,?qst?in?enumerate(question_list):
??x?=?input("第{:>2d}题:{}".format(i+1,?qst[0]))
??if?int(x)?!=?int(qst[1]):
????wrong?+=?str(i+1)?+?"?"
w_item?=?wrong.split()
print("回答正确{}道题目。".format(len(question_list)?-?len(w_item)))
print("回答错误的题号是:{}".format(wrong))
这是一个二进制数1011101的奇偶校验,其中最右边的一位是校验位,用于确保该二进制数中的1的个数为奇数。具体实现方式是在该二进制数中加入一位校验位,使得总共有偶数位,然后校验位的值设为使得总共有奇数个1的值,比如这个例子中的校验位为1,因为该数中有4个1。
需要注意的是,这种奇偶校验只能检测出二进制数中出现了偶数个错误,如果出现了奇数个错误,则无法检测出来。同时,这种校验方式也不能纠正错误,只能检测错误的存在。
以下是Python实现的奇偶校验码生成和校验的代码示例:
def generate_parity_bit(data):
# Count number of ones in binary representation of data
ones_count = 0
for c in bin(data)[2:]:
ones_count += int(c)
# If there are an odd number of ones, parity bit is 0
# Otherwise, parity bit is 1
if ones_count % 2 == 0:
return 1
else:
return 0
def add_parity_bits(data):
# Generate parity bit for each byte in data
parity_bits = [generate_parity_bit(byte) for byte in data]
# Combine original data and parity bits into a new bytearray
result = bytearray()
for i in range(len(data)):
result.append(data[i])
result.append(parity_bits[i])
return result
def check_parity_bits(data_with_parity):
# Check parity bit for each byte in data_with_parity
for i in range(len(data_with_parity)):
if i % 2 == 0: # Skip parity bits
continue
byte = data_with_parity[i-1]
parity_bit = data_with_parity[i]
if generate_parity_bit(byte) != parity_bit:
return False
return True
其中,generate_parity_bit函数用于计算一个字节的奇偶校验位,add_parity_bits函数用于给一段二进制数据加上奇偶校验位,check_parity_bits函数用于检查一段带有奇偶校验位的二进制数据是否正确。