python-3.x 运行循环10,000次,以测试预期值

iyfjxgzm  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(153)

玩一个2人游戏,玩家A和B轮流从袋子里取出石头。
10颗宝石,9颗白色,1颗黑色
如果你抽到黑石头,你就输了。
假设你轮流抽石头,先走是优势、劣势还是中性?
我知道这可以用条件概率来解决,但我也想用大量的样本数据来证明这一点

  1. import random
  2. import os
  3. import sys
  4. stones = 4
  5. player1Wins = 0
  6. player2Wins = 0
  7. no_games = 100000
  8. gameCount = 0
  9. fatal_stone = random.randint(1, int(stones))
  10. picked_stone = random.randint(1, int(stones))
  11. def pick_stone(self, stones):
  12. for x in range(1, int(stones) + 1):
  13. if picked_stone == fatal_stone:
  14. if (picked_stone % 2) == 0:
  15. player2Wins += 1 print("Player 2 won")
  16. break
  17. if (picked_stone % 2) == 1:
  18. player1Wins += 1
  19. print("Player 1 won")
  20. break
  21. else:
  22. stones -= 1 picked_stone = random.randint(1, int(stones))
  23. self.pick_stone()
  24. pick_stone()
  25. # def run_games(self, no_games): #for i in range(1, int(no_games) + 1): #gameCount = i #self.pick_stone()
  26. print(fatal_stone)
  27. print(picked_stone)
  28. print(int(fatal_stone % 2))
  29. print(int(picked_stone % 2))
  30. print(gameCount)
  31. print("Player 1 won this many times: " + str(player1Wins))
  32. print("Player 2 won this many times: " + str(player2Wins))
jmp7cifd

jmp7cifd1#

下面的代码是有效的,它表明无论谁先玩,双方获胜的机会都是相等的。

  1. import random
  2. import os
  3. import sys
  4. num_stones = 4
  5. no_games = 100000
  6. player1Wins = 0
  7. player2Wins = 0
  8. def pick_stone(player: int, stones: list, fatal_stone: int):
  9. global player1Wins, player2Wins
  10. picked_stone = random.choice(stones)
  11. stones.remove(picked_stone)
  12. if (picked_stone == fatal_stone):
  13. if player == 1:
  14. player2Wins += 1
  15. else:
  16. player1Wins += 1
  17. return False
  18. return True
  19. def run_games(no_games: int):
  20. for _ in range(no_games):
  21. stones = [i for i in range(num_stones)]
  22. fatal_stone = random.choice(stones)
  23. # player 1 and 2 pick stones in turn
  24. player = 1
  25. playing = True
  26. while playing:
  27. playing = pick_stone(player, stones, fatal_stone)
  28. player = player % 2 + 1
  29. print(f"Total rounds: {no_games}")
  30. print("Player 1 won this many times: " + str(player1Wins))
  31. print("Player 2 won this many times: " + str(player2Wins))
  32. run_games(no_games)
展开查看全部

相关问题