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

为何possibility_1与possibility_2数值始终未变化?求掷硬币模拟代码修复

问题排查与修复方案
  • 核心错误:类型不匹配导致条件永远不成立
    你把三个随机数拼接成了字符串(例如"1,1,0"),但判断条件里用的是元组(例如(1,1,0))。字符串和元组属于不同类型,永远不可能相等,所以possibility_1和possibility_2的累加逻辑永远不会触发。

  • 额外优化建议

    • 避免用list作为自定义变量名,它是Python内置类型,改用coin_sides这类语义化名称更清晰
    • 代码里没用到math模块,可以直接删除
    • 无限while True循环会一直运行,建议添加模拟次数限制,方便控制运行时长

修复后的完整代码

import random

possibility_1 = 0
possibility_2 = 0
# 设置总模拟次数,避免无限循环
total_trials = 1000
current_trial = 0

coin_sides = [0, 1]

while current_trial < total_trials:
    number_1 = random.choice(coin_sides)
    number_2 = random.choice(coin_sides)
    number_3 = random.choice(coin_sides)
    
    # 用元组存储结果,和判断条件的类型保持一致
    number_total = (number_1, number_2, number_3)
    
    if number_total == (1,1,0) or number_total == (0,0,1):
        possibility_1 += 1

    if number_total == (1,1,1) or number_total == (0,0,0):
        possibility_2 += 1   
    
    print(f"{number_total}  possibility_1={possibility_1}  possibility_2={possibility_2}")
    current_trial += 1

# 输出最终统计概率
print(f"\n模拟结束:")
print(f"组合(1,1,0)/(0,0,1)出现概率:{possibility_1/total_trials:.2%}")
print(f"组合(1,1,1)/(0,0,0)出现概率:{possibility_2/total_trials:.2%}")

关键修改说明

  1. 将number_total改为元组类型,和判断条件中的元组匹配,确保条件判断能正常触发累加
  2. 添加了模拟次数限制,避免程序无限运行
  3. 使用f-string简化打印语句,提升可读性
  4. 增加了最终概率计算输出,更贴合统计需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:18:35