There are 1, 2, 3, 4 number card in a bag.
When there are 8 balls in box_b, what is the probability that the number of black balls in the box is 2?
import math
#흰공=0 검은공=1
box_b = list()
#조건부확률 = box_b 원소 개수 8개(=e)이면서 1이 2개(=f)일 확률 / e 확률
cnt_e = 0
cnt_ef = 0
for i in range(1, 5) :
if i == 1 :
box_b.append(0)
if i == 2 or i == 3 :
box_b.append([0, 1])
if i == 4 :
box_b.append([0, 0, 1])
for j in range(1, 5) :
if j == 1 :
box_b.append(0)
if j == 2 or j == 3 :
box_b.append([0, 1])
if j == 4 :
box_b.append([0, 0, 1])
for k in range(1, 5) :
if k == 1 :
box_b.append(0)
if k == 2 or k == 3 :
box_b.append([0, 1])
if k == 4 :
box_b.append([0, 0, 1])
for l in range(1, 5) :
if l == 1 :
box_b.append(0)
if l == 2 or l == 3 :
box_b.append([0, 1])
if l == 4 :
box_b.append([0, 0, 1])
print(box_b)
Output should be like [0, [0,1], [0,0,1], [0,1]], [...]
, but it's output is [0, [0,1], 0, [0,1], 0, [0,1], 0, [0,1] .... (very long list)...] [..]
What's wrong with my code?
++ It is not duplicate : I tried i == 2 or i == 3(seperation of two conditions), but it isn't major problem which I look for. There are still problems.
This is how simulating the problem would look like:
import random
random.seed(1)
def calc_prob(bag, sims):
def pick():
card = None
while card is None:
card = random.choice(bag)
if card is not None:
bag[card] = None
break
return card
eights = 0
blacks = 0
for _ in range(sims):
box_b = []
for _ in range(4):
card = pick()
if card == 1:
box_b.append(0)
elif card == 2 or card == 3:
box_b.extend([0, 1])
elif card == 4:
box_b.extend([0, 0, 1])
if len(box_b) == 8:
eights += 1
if box_b.count(1) == 2:
blacks += 1
return blacks / eights if eights else 0
sims = 100000
bag = [1, 2, 3, 4] * (sims + 1)
print(calc_prob(bag, sims))
0.08484606447865234