gpt4 book ai didi

Python 未完成 for 循环

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:37 27 4
gpt4 key购买 nike

我刚刚开始学习 python,我想看看是否可以制作 monty Hall 问题的 python 版本。当我使用 1 或 2 次迭代时,一切似乎都在小范围内工作,但超过此后,一切都不起作用了。 for 循环没有完成我想要的迭代次数。

import random

def problem(tests):

wins = 0
losses = 0
doors = ["goat", "car", "goat"]

for test in range(tests):
#we shuffle the doors
random.shuffle(doors)
#the player picks a door
choice = random.choice(doors)
#monty chooses a door
montychoice = random.choice(doors)
while montychoice != 'car' or montychoice == choice:
montychoice = random.choice(doors)

#if the player's door is a car, he losses
if choice == 'car':
losses += 1
print 'goat'
elif choice == 'goat':
wins += 1
print 'car'

print "Switching wins: %d" % wins
print "Switching loses: %d" % losses

problem(100)

最佳答案

问题不在于 for 循环,而在于 while 循环。

为了让 while 循环中断,montychoice 必须等于 car AND 玩家的选择。但是,如果玩家的选择不是汽车,而是山羊怎么办? while 循环永远不会中断。

我认为您的 while 循环需要 and 而不是 or 。这样,如果任一条件不满足,循环就会中断。

关于Python 未完成 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511845/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com