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

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

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

import random
import os
import sys

stones = 4
player1Wins = 0
player2Wins = 0

no_games = 100000
gameCount = 0

fatal_stone = random.randint(1, int(stones))

picked_stone = random.randint(1, int(stones))

def pick_stone(self, stones):
    for x in range(1, int(stones) + 1):
        if picked_stone == fatal_stone:
            if (picked_stone % 2) == 0:
                player2Wins += 1 print("Player 2 won")
                break
            if (picked_stone % 2) == 1:
                player1Wins += 1
                print("Player 1 won")
                break
            else:
                stones -= 1 picked_stone = random.randint(1, int(stones))
            self.pick_stone()

pick_stone()

# def run_games(self, no_games): #for i in range(1, int(no_games) + 1): #gameCount = i #self.pick_stone()

print(fatal_stone)
print(picked_stone)

print(int(fatal_stone % 2))
print(int(picked_stone % 2))

print(gameCount)
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
jmp7cifd

jmp7cifd1#

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

import random
import os
import sys

num_stones = 4

no_games = 100000

player1Wins = 0
player2Wins = 0

def pick_stone(player: int, stones: list, fatal_stone: int):
    global player1Wins, player2Wins
    
    picked_stone = random.choice(stones)
    stones.remove(picked_stone)
    if (picked_stone == fatal_stone):
        if player == 1:
            player2Wins += 1
        else:
            player1Wins += 1
        return False
    return True


def run_games(no_games: int): 
    for _ in range(no_games): 
        stones = [i for i in range(num_stones)]
        fatal_stone = random.choice(stones)
        
        # player 1 and 2 pick stones in turn
        player = 1
        playing = True
        while playing:
            playing = pick_stone(player, stones, fatal_stone)
            player = player % 2 + 1

    print(f"Total rounds: {no_games}")
    print("Player 1 won this many times: " + str(player1Wins))
    print("Player 2 won this many times: " + str(player2Wins))

run_games(no_games)

相关问题