Running a loop 10,000 times in order to test expected value

138 views Asked by At

Playing a 2 person game where player A and B take turns drawing stones out of a bag.

10 stones, 9 white, 1 black

You lose if you draw the black stone.

Assuming you alternate drawing stones, is going first an advantage, disadvantage, or neutral?

I'm aware that this can be solved using conditional probability, but I'd like to also prove it by using significant sample size data

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))
1

There are 1 answers

0
Frank On

The following code works. And it suggests that both players' chances of winning are equal, regardless of who plays first.

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)