首页 > 解决方案 > 当函数返回 True 时中断无限循环

问题描述

我设置了一个代码,如果它有效,它将在嵌套函数最终返回 True 时停止 while 循环。但是,每次我尝试在这个阶段对其进行测试时,它似乎都没有结束。

当前程序的目标是模拟山上房子的背叛和博德之门的背叛中鬼屋滚动机制,并模拟一个实验来确定在开始鬼屋之前会找到多少个预兆房间。下一阶段将是设置一个数组和 for 循环以显示每个游戏长度的相应概率。

import random as rd

import numpy as np


Betrayald6 = np.array([0,0,1,1,2,2],dtype='int')

def fairdicesum(dice):
    sum = 0
    for i in range(dice.shape[0]):
        single = rd.choice(dice[i,:])
        sum = sum + single
    return sum

def HauntRoll(CurseCount, Game = 'House on the Hill'):
    if Game == 'House on the Hill':
        dice = np.zeros([6,6])
    elif Game == "Baldur's Gate":
        dice = np.zeros([CurseCount,6])
    else:
        print ('No dice')
    for i in range(len(dice)):
        dice[i] = Betrayald6
    Roll = fairdicesum(dice)
    if Game == 'House on the Hill':
        if Roll < CurseCount:
            Haunt = 1
        else:
            Haunt = 0
    elif Game == "Baldur's Gate":
        if Roll < 6:
            Haunt = 0
        else:
            Haunt = 1
        return Haunt

def HowLongToHaunt(Game = 'House on the Hill'):
    CurseCount = 0
    while True:
        CurseCount = CurseCount + 1
        Result = HauntRoll(CurseCount,Game=Game)
        if Result == 1:
            break
    return CurseCount

我已经测试了fairdicesum功能和HauntRoll功能,它们都可以工作。有没有办法改进HowLongToHaunt函数的代码,以便它更有效地运行?

顺便说一句,这是我第一次使用 while 循环,而不是 for 循环,所以它可能是循环的问题,尽管我没有收到错误消息。

标签: pythonwhile-loop

解决方案


使此运行更有效的一种方法是替换

def HowLongToHaunt(Game = 'House on the Hill'):
    CurseCount = 0
    while True:
        CurseCount = CurseCount + 1
        Result = HauntRoll(CurseCount,Game=Game)
        if Result == 1:
            break
    return CurseCount

def HowLongToHaunt(Game = 'House on the Hill'):
    CurseCount = 0
    while Result != 1:
        CurseCount = CurseCount + 1
        Result = HauntRoll(CurseCount,Game=Game)
    return CurseCount

推荐阅读