私はちょうどpythonを学び始めました。私はmontyホールの問題のpython版を作ることができるかどうかを楽しみにしていました。私は1回または2回の繰り返しを使用するが、何も動作していないと、すべてが小規模で動作しているようだ。 forループは、私が望む反復の量を終了していません。Pythonがループを終了しない
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)
whileループでprintステートメントを追加してみてください。私が見るコードの唯一のブロックです。したがって、何らかの理由で終了条件が満たされない場合は、whileループに永遠に留まります。 – reticentroot
これにはrandom.choice()を使用したくありません。この問題では、ドアの裏側だけでなく、どのドアが選択されているかを知ることが重要です。実際のドアのインデックスを取得するにはrandom.randint(0,2)またはrandom.randrange(len(doors))を使用してください。 – Cuagau