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

如何修正Python中时间戳处理的逻辑错误,实现a、b、c的正确计算?

问题分析

原代码的核心问题在于没有按日志的时间顺序追踪命令的上下文关联,而是将每个命令的时间戳单独存储为列表,导致无法建立PRECHARGE→ACTIVE→WRITING的对应关系,且直接比较列表的逻辑完全不符合需求。

修正思路
  1. 按日志行的顺序遍历,追踪关键状态:最近一次PRECHARGE的时间、最近一次ACTIVE的时间。
  2. 对每个WRITING,判断它属于a、b还是c的范畴,并标记已使用的WRITING。
  3. 将时间戳转换为整数进行数值比较,避免字符串比较的误差(比如"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}")
代码说明
  1. 状态追踪:通过last_precharge和last_active记录最近的预充电和激活命令时间,确保能按顺序关联后续的WRITING命令。
  2. 条件判断:
    • a的判断:必须存在PRECHARGE→ACTIVE→WRITING的顺序,且时间依次递增。
    • b的判断:仅存在ACTIVE→WRITING的顺序,且没有PRECHARGE前置,同时该WRITING未被a占用。
  3. 已使用标记:用used_writings集合记录被a或b使用的WRITING行号,避免重复计算。
  4. c的计算:统计所有WRITING的总数,减去已被a、b使用的数量,得到剩余的WRITING数量。
执行结果

运行修正后的代码,输出将符合预期:

a: 2
b: 1
c: 1

内容的提问来源于stack exchange,提问作者CJ. T

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:05:25