[英]Probability calculation in python
My problem is: I have 12 players, with 3 of them being named A, B and C, respectively.我的问题是:我有 12 个玩家,其中 3 个分别被命名为 A、B 和 C。 12 players are being divided into 2 groups, 6 people each.
12名选手被分成2组,每组6人。 I need to calculate the probability of player A and B being in the same team, and player C being in thе eopposite one.
我需要计算球员 A 和 B 在同一支球队中的概率,而球员 C 在相反的球队中的概率。 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.任何帮助表示赞赏。
The number of ways to fill 1 list of six total = 12!/(6! * 6!) comb(12,6)
填充 1 个共 6 个列表的方法数 = 12!/(6! * 6!)
comb(12,6)
The number of ways to fill a list of six (including A and B and not C) = 9!/(4! * 5!) comb(9, 4)
填充六种列表的方法数(包括 A 和 B,不包括 C)= 9!/(4! * 5!)
comb(9, 4)
Also, want to find (not A and not B and C) = 9!/(5! * 4!) comb(9, 5)
另外,想要找到 (not A and not B and C) = 9!/(5! * 4!)
comb(9, 5)
>>> from math import comb
>>> comb(12, 6)
924
>>> comb(9, 4) + comb(9, 5)
252
>>> 252 / 924
0.2727272727272727
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:
这个想法是在你的测试代码上循环多次,它不是 100% 准确,但我认为对你来说已经足够了:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.