You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何用for循环替换count方法统计二进制序列中的0的数量

奇校验统计逻辑For循环实现方案

核心修改逻辑

直接替换原函数中result = Byte.count('0')的内置方法调用即可,改动逻辑如下:

  • 初始化0的计数变量为0
  • 遍历输入字节字符串的每一个字符
  • 每匹配到字符为'0'时,计数变量加1
  • 后续奇偶性判断逻辑和原有实现完全一致,无需调整

完整修改后代码

import random
def random_binary_sequence(n):
  bit = ""
  for i in range(0, n, 1):
    random_bit = str(random.randint(0, 1))
    bit += random_bit
  return bit

test_byte = random_binary_sequence(7) + " | 0"

def OddParity(Byte):
  # 替换count()方法的for循环统计逻辑
  zero_count = 0
  for char in Byte:
      if char == '0':
          zero_count += 1
  # 原有判断逻辑保持不变
  if zero_count % 2 == 0:
    print("\n" + "This sequence is incorrect and must be corrected.", "\n")
    return False
  else:
    print("\n" + "This sequence is correct." "\n")
    return True

print("Random test byte given: " + test_byte)
print(OddParity(test_byte))

运行效果示例

和原有代码输出完全一致:

Random test byte given: 1011010 | 0

This sequence is incorrect and must be corrected. 

False

内容的提问来源于stack exchange,提问作者zаѓатhᵾѕтѓа

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:36:08