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

如何在Python中检测Brainf*ck程序是否陷入超5秒的循环?

给Brainfuck解释器添加长循环超时检测(超过5秒)

我正在用Python编写一个生成并运行随机Brainfuck程序的工具,现有一个解释器,需要添加**检测长循环(运行超过5秒即终止)**的功能。以下是当前的解释器代码:

while i < len(code):
    if code[i] == '<':
        if pointerLocation > 0:
            pointerLocation -= 1
    elif code[i] == '>':
        pointerLocation += 1
        if len(array) <= pointerLocation:
            array.append(0)
    elif code[i] == '+':
        array[pointerLocation] += 1
    elif code[i] == '-':
        if array[pointerLocation] > 0:
            array[pointerLocation] -= 1
    elif code[i] == '.':
        print(array[pointerLocation], chr(array[pointerLocation]))
        result += chr(array[pointerLocation])
    elif code[i] == ',':
        #x = input("Input (1 CHARACTER!):")
        x = 'h'
        #increase time if user inputs
        t1 += 5
        try:
            y = int(x)
        except ValueError:
            y = ord(x)
        array[pointerLocation] = y
    elif code[i] == '[':
        if array[pointerLocation] == 0:
            open_braces = 1
            while open_braces > 0 and i+1 < len(code):
                i += 1
                if code[i] == '[':
                    open_braces += 1
                elif code[i] == ']':
                    open_braces -= 1
    elif code[i] == ']':
        # you don't need to check array[pointerLocation] because the matching '[' will skip behind this instruction if array[pointerLocation] is zero
        open_braces = 1
        while open_braces > 0:
            if t > 5:
                return [result,code,t]
                print(123)
            i -= 1
            if code[i] == '[':
                open_braces -= 1
            elif code[i] == ']':
                open_braces += 1
        # i still gets incremented in your main while loop
        i -= 1
    i += 1

解决方案:实现全局超时检测

原代码里的超时逻辑仅在]处理中局部检查,且t变量未正确初始化计时,完全起不到全局检测的作用。要实现可靠的超时检测,需要在整个解释器运行过程中持续监控时间:

  1. 导入time模块用于获取时间戳计算运行时长
  2. 在解释器启动时记录起始时间点
  3. 在主循环的每次迭代开头、以及循环跳转过程中检查是否超过5秒,一旦超时立即终止并返回当前状态
  4. 移除return之后永远不会执行的无效print(123)语句

修改后的完整代码:

import time

def interpret_bf(code):
    array = [0]
    pointerLocation = 0
    result = ""
    i = 0
    start_time = time.time()  # 记录解释器启动时间
    t1 = 0  # 初始化用户输入额外计时变量
    
    while i < len(code):
        # 每次指令执行前先检查超时
        elapsed = time.time() - start_time + t1
        if elapsed > 5:
            return [result, code, elapsed]
        
        if code[i] == '<':
            if pointerLocation > 0:
                pointerLocation -= 1
        elif code[i] == '>':
            pointerLocation += 1
            if len(array) <= pointerLocation:
                array.append(0)
        elif code[i] == '+':
            array[pointerLocation] += 1
        elif code[i] == '-':
            if array[pointerLocation] > 0:
                array[pointerLocation] -= 1
        elif code[i] == '.':
            print(array[pointerLocation], chr(array[pointerLocation]))
            result += chr(array[pointerLocation])
        elif code[i] == ',':
            #x = input("Input (1 CHARACTER!):")
            x = 'h'
            #increase time if user inputs
            t1 += 5
            try:
                y = int(x)
            except ValueError:
                y = ord(x)
            array[pointerLocation] = y
        elif code[i] == '[':
            if array[pointerLocation] == 0:
                open_braces = 1
                while open_braces > 0 and i+1 < len(code):
                    i += 1
                    if code[i] == '[':
                        open_braces += 1
                    elif code[i] == ']':
                        open_braces -= 1
        elif code[i] == ']':
            open_braces = 1
            while open_braces > 0:
                # 循环跳转过程中也检查超时
                elapsed = time.time() - start_time + t1
                if elapsed > 5:
                    return [result, code, elapsed]
                i -= 1
                if code[i] == '[':
                    open_braces -= 1
                elif code[i] == ']':
                    open_braces += 1
            # i still gets incremented in your main while loop
            i -= 1
        i += 1
    # 正常结束时返回结果
    elapsed = time.time() - start_time + t1
    return [result, code, elapsed]

关键改动说明

  • 新增start_time记录启动时间,结合time.time()实时计算总运行时长
  • 将用户输入额外增加的t1时间纳入超时计算,符合原代码的注释逻辑
  • 在主循环开头和]的跳转循环中都加入超时检查,避免长循环绕过检测
  • 移除原代码中return后的无效print语句
  • 确保无论正常结束还是超时终止,都返回统一格式的结果(当前输出、代码、耗时)

内容的提问来源于stack exchange,提问作者Unresolved

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:45:56