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

求助:Python计算魔方破解年限时遇变量访问及定时更新问题

问题1:内部函数无法识别外层cubers变量的原因

  • Python作用域规则中,内部函数如果要修改外层函数的变量,默认会将该变量识别为内部局部变量,你在cubersCount里直接写cubers = cubers +5,解释器会认为你要给内部局部变量cubers赋值,计算等号右侧的时候内部的cubers还没定义,就会抛出未定义报错。
  • 解决方法是在内部函数开头加nonlocal cubers声明,告诉解释器这个变量调用的是外层函数的变量:
def cubersCount():
    nonlocal cubers
    cubers = cubers +5

问题2:实现每24小时cubers加5的逻辑

根据你的核心需求是计算总耗时的场景,分两种方案实现:

方案1:模拟时间流逝计算总年数(推荐,无需真实等待)

不需要实际等待24小时更新数值,直接用逻辑模拟每天的玩家数量变化、累计打乱次数即可算出结果:

def calculate_total_years():
    # 魔方总打乱状态数
    total_scrambles = 43252003274489856000
    # 初始玩家数
    cubers = 6000000
    # 单玩家每秒可生成的打乱数,和你原有代码的/25逻辑对齐
    scrambles_per_cuber_per_second = 25
    # 一天总秒数
    seconds_per_day = 24 * 60 * 60
    total_days = 0
    finished_scrambles = 0
    
    while finished_scrambles < total_scrambles:
        # 统计当日生成的总打乱数
        daily_scrambles = cubers * scrambles_per_cuber_per_second * seconds_per_day
        finished_scrambles += daily_scrambles
        # 每日新增5名玩家
        cubers += 5
        total_days += 1
    
    # 总天数转年数
    total_years = total_days / 365
    print(f"遍历所有状态需要约{total_years:.2e}年")

calculate_total_years()

方案2:真实定时每24小时更新玩家数(仅用于需实时运行的场景)

如果确实需要程序持续运行、自动定时更新玩家数,可以用time.sleep配合后台线程实现:

import time
import threading

def yearsTime():
    scrambles = 43252003274489856000
    cubers = 6000000

    def cubersCount():
        nonlocal cubers
        cubers += 5
        print(f"玩家数已更新为:{cubers}")
    
    # 后台定时更新线程,不阻塞主逻辑运行
    def update_cubers_regularly():
        while True:
            # 86400秒=24小时
            time.sleep(86400)
            cubersCount()
    
    threading.Thread(target=update_cubers_regularly, daemon=True).start()
    
    # 原有计算逻辑
    scrambles = scrambles / 25 / 24 / 60 / 24 / 365
    print(scrambles)

yearsTime()
# 保持主程序不退出
while True:
    time.sleep(3600)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:24:07