我的目标是获得“脸红”的概率。
下面是我的代码:
from random import *
#generating deck
deck = []
for i in range(4):
for value in range(13):
deck.append(100*i + value)
sim = 100000
hearts = 0
spades = 0
diamonds = 0
clubs = 0
flush = 0
for i in range(sim):
#generating hand
hand = []
shuffle(deck)
for i in range(5):
hand.append(deck[i])
#checking for "flush"
for i in range(5):
if hand[i] < 100:
hearts += 1
elif hand[i] < 200:
spades += 1
elif hand[i] < 300:
diamonds += 1
elif hand[i] < 400:
clubs += 1
if hearts == 5 or spades == 5 or diamonds == 5 or clubs == 5:
flush += 1
#probability
print(flush/sim)实际概率显然接近0.03,但这并不是得到的结果,代码中的逻辑是否有问题?
发布于 2021-10-14 20:24:23
您可以利用itertools模块来做到这一点:
from itertools import product
import random
suits = ['s', 'h', 'd', 'c']
cpips = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
deck = [c for c in product(cpips, suits)] # combinations of suits and values
sim = 10000
flushes = 0
for s in sim:
random.shuffle(deck)
hand = []
for i in range(5):
hand.append(deck[i])
# check that all suits are matching
if all([hand[0][1] == c[1] for c in hand]):
flushes += 1
prob = flushes / sim如果你想添加更多的随机性,或者让它更像纸牌游戏,你可以为其他玩家的数量创建一个参数p,并在每次迭代后让i增加那么多:
p = 5
for s in sim:
random.shuffle(deck)
hand = []
while len(hand) <=5:
hand.append(deck[i])
i += p
# check that all suits are matching
if all([hand[0][1] == c[1] for c in hand]):
flushes += 1https://stackoverflow.com/questions/69576544
复制相似问题