Python3.6.3
"""
52张扑克:
['♥2', '♦2', '♣2', '♠2', '♥3', ... ]
draw(n) 抽取n张牌
is_same_flower(pokers) 判断同花
is_straight(pokers) 判断顺子
is_flush(pokers) 判断同花顺
"""
import random
__all__ = ['draw', 'is_same_flower', 'is_straight', 'is_flush']
class Poker():
def __init__(self):
colors = ('♥', '♦', '♣', '♠') # 所有花色
self.all_nums = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A') # 所有牌号
self.all_pokers = tuple([c + n for c in colors for n in self.all_nums]) # 生成所有牌
def draw(self, n: int) -> list:
"""随机抽取n张牌"""
return random.sample(self.all_pokers, n)
def is_same_flower(self, pokers: list):
"""
判断同花,如果花色只有一种,即为同花
:return: True / False
"""
flowers = [p[0] for p in pokers] # 花色列表
return True if len(set(flowers)) == 1 else False
def is_straight(self, pokers: list):
"""
判断顺子,如果这几张牌在13张牌中的位置是等差为1的数列,即为顺子。
:return: True / False
"""
ies = [self.all_nums.index(p[1:]) for p in pokers] # indexes 索引列表
ies.sort()
return True if ies[-1] - ies[0] == len(ies) - 1 else False
def is_flush(self, pokers: list):
"""
判断同花顺
:return: True / False
"""
return True if self.is_same_flower(pokers) and self.is_straight(pokers) else False
def _test():
poker = Poker()
i = 0
for _ in range(10 ** 6):
my_pokers = poker.draw(5)
if poker.is_flush(my_pokers):
print(my_pokers)
i += 1
# i += int(poker.is_flush(my_pokers))
print(i)
_poker = Poker()
draw = _poker.draw
is_same_flower = _poker.is_same_flower
is_straight = _poker.is_straight
is_flush = _poker.is_flush
if __name__ == '__main__':
_test()
重点: