python - 当函数返回 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 循环,所以它可能是循环的问题,尽管我没有收到错误消息。
解决方案
使此运行更有效的一种方法是替换
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
推荐阅读
- angular - 我映射的 observable 的结果是……一个 observable?(通过 switchMap 运行后)
- python - 为什么我必须在 python 源代码中嵌入代码版本有什么实际原因吗?
- java - 如何将应用程序映射到 docker 卷
- git - 如何在 git 存储库中获取新的子目录?
- adal-deprecation - 适用于 SharePoint Online 的 ADAL 到 MSAL
- java - Spring:嵌套实体保存空值问题
- python - 具有子组的互斥组 - argparse
- mysql - 递增表中值的连续出现次数
- c - C 语言是否需要对逻辑语句进行短路/最小评估?
- swift - SwiftUI ForEach 循环索引始终为 0