如何修正Python中时间戳处理的逻辑错误,实现a、b、c的正确计算?
问题分析
原代码的核心问题在于没有按日志的时间顺序追踪命令的上下文关联,而是将每个命令的时间戳单独存储为列表,导致无法建立PRECHARGE→ACTIVE→WRITING的对应关系,且直接比较列表的逻辑完全不符合需求。
修正思路
- 按日志行的顺序遍历,追踪关键状态:最近一次
PRECHARGE的时间、最近一次ACTIVE的时间。 - 对每个
WRITING,判断它属于a、b还是c的范畴,并标记已使用的WRITING。 - 将时间戳转换为整数进行数值比较,避免字符串比较的误差(比如
"0115"转为115更易比较)。
修正后的代码
import re # 初始化状态变量和计数器 last_precharge = None last_active = None used_writings = set() a = b = c = 0 with open("page_stats.txt", "r") as f: for line in f: m = re.split(r"\s*\|\s*", line.strip()) # 过滤表头和分隔线,只处理有效数据行 if len(m) > 3 and re.match(r"\d+", m[1]): line_num = int(m[1]) timestamp = int(m[2]) command = m[3].strip() # 更新最近的命令状态 if command == "PRECHARGE": last_precharge = timestamp elif command == "ACTIVE": last_active = timestamp elif command == "WRITING": # 判断是否符合a的条件:PRECHARGE→ACTIVE→WRITING的时间递增顺序 if last_precharge is not None and last_active is not None: if last_active > last_precharge and timestamp > last_active: a += 1 used_writings.add(line_num) # 判断是否符合b的条件:无PRECHARGE前置,且ACTIVE→WRITING时间递增,未被a占用 elif last_precharge is None and timestamp > last_active and line_num not in used_writings: b += 1 used_writings.add(line_num) # 统计总WRITING数量,减去已使用的得到c total_writings = 0 with open("page_stats.txt", "r") as f: for line in f: m = re.split(r"\s*\|\s*", line.strip()) if len(m) > 3 and re.match(r"\d+", m[1]) and m[3].strip() == "WRITING": total_writings += 1 c = total_writings - len(used_writings) # 输出结果 print(f"a: {a}") print(f"b: {b}") print(f"c: {c}")
代码说明
- 状态追踪:通过
last_precharge和last_active记录最近的预充电和激活命令时间,确保能按顺序关联后续的WRITING命令。 - 条件判断:
- a的判断:必须存在
PRECHARGE→ACTIVE→WRITING的顺序,且时间依次递增。 - b的判断:仅存在
ACTIVE→WRITING的顺序,且没有PRECHARGE前置,同时该WRITING未被a占用。
- a的判断:必须存在
- 已使用标记:用
used_writings集合记录被a或b使用的WRITING行号,避免重复计算。 - c的计算:统计所有
WRITING的总数,减去已被a、b使用的数量,得到剩余的WRITING数量。
执行结果
运行修正后的代码,输出将符合预期:
a: 2 b: 1 c: 1
内容的提问来源于stack exchange,提问作者CJ. T
相关产品推荐
相关产品推荐

