Python 扑克

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()

 重点:

  1. random.sample(population, k)
    1. 从population中随机选出k个元素组成一个列表返回
    2. 返回的列表中k个元素的顺序也是随机的
    3. 如果是整数范围就用range
    4. k不能超出长度
  2. 判断同花,即是判断花色相同否,直接看set后的数量即可
  3. 判断顺,即是不是等差为1的数列,首尾相差长度-1即是
  4. 单前下划线能且仅能限制`from xx import *`格式的导入,__all__也是。

你可能感兴趣的:(Python)