Search code examples
pythonprobability

Probability calculation in python


My problem is: I have 12 players, with 3 of them being named A, B and C, respectively. 12 players are being divided into 2 groups, 6 people each. I need to calculate the probability of player A and B being in the same team, and player C being in thе eopposite one. Math is not my strongsuit, because im pretty sure this is not a hard thing to calculate, but i would be really grateful if you could help me with this one. Here is what i wrote so far:

import random

playersnumb = 12
players = list(range(12))

A = random.choice([x for x in range(12)])

B = random.choice([x for x in range(12) if x != A])

C = random.choice([x for x in range(12) if (x != A) and (x != B)])

random.shuffle(players)
team1 = (players[:6])
team2 = (players[6:])

if A in team1:
    print("Player A is in team 1")
else:
    print("Player A is in team 2")
if B in team1:
    print("Player B is in team 1")
else:
    print("Player B is in team 2")
if C in team1:
    print("Player C is in team 1")
else:
    print("Player C is in team 2")

Any help is appreciated.


Solution

  • I wrote a little bit based on your code. The idea is to loop multiple times over your test code, it is not 100% accurate, but i think good enough for you:

    import random
    
    
    def calculate(playercount: int = 12) -> bool:
        players = list(range(playercount))
    
        player_a = random.choice([x for x in range(playercount)])
    
        player_b = random.choice([x for x in range(playercount) if x != player_a])
    
        player_c = random.choice([x for x in range(playercount) if (x != player_a) and (x != player_b)])
    
        random.shuffle(players)
        team1 = (players[:playercount//2])
        team2 = (players[playercount//2:])
    
        # That are your "positive" events
        return (player_a in team1 and player_b in team1 and player_c in team2) or\
               (player_a in team2 and player_b in team2 and player_c in team1)
    
    
    def calculate_all(runtimes: int = 100000) -> float:
        counter = 0
        # count all poyitive events
        for i in range(runtimes):
            if calculate():
                counter += 1
    
        # return how often they appeared, based on all tests
        return counter / runtimes
    
    
    print("The probability is about {} %".format(calculate_all() * 100))