我创建了一个类,可以有效地从 52 张牌组中随机发一张扑克牌。然后我写了几行代码来模拟 52 次绘制的 100K 模拟,因为我想知道分布是否正确实现。当我这样做时,我意识到运行 sim 需要 87 秒。这对我来说似乎很长一段时间。任何人都可以指出#2 中的一些可能使它变得如此缓慢的事情吗?
import time
import random as rand
import numpy as np
class PlayingCard:
ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']
def __init__(self, rank = None, suit = None):
if rank is None: self.rank = PlayingCard.ranks[rand.randint(0,12)]
elif rank in PlayingCard.ranks: self.rank = rank
else: raise NameError('Invalid rank')
if suit is None: self.suit = PlayingCard.suits[rand.randint(0,3)]
elif suit in PlayingCard.suits: self.suit = suit
else: raise NameError('Invalid suit')
def identity(self):
return (self.rank,self.suit)
#2
start = time.clock()
deck = zip(PlayingCard.ranks*4,PlayingCard.suits*13)
mat = [[PlayingCard().identity() for x in range(52)] for y in range(100000)]
res = [[(y.count(x)/52.0) for x in deck] for y in mat]
mean = [np.mean([res[y][x] for y in range(len(res))]) for x in range(52)]
end = time.clock() - start
print end