创建一个函数,生成排名高于base_card的所有卡的列表?

时间:2013-04-02 17:04:03

标签: python

我必须创建一个函数higher_in_rank,它使用一张牌,base_card,并生成一个列表,列出排名高于base_card的排名,按排名顺序排序。卡的排名如下:

  • 就西装而言,俱乐部低于钻石,低于心形,低于黑桃,无论其价值如何。
  • 如果两张牌有相同的牌,则价值较大的牌的牌号较高。

例如:

 higher_in_rank(card('spades', 8)) => [card('spades', 9), card('spades', 10)] 
 higher_in_rank(card('diamonds', 6)) =>
    [card('diamonds',7), card('diamonds', 8), ..., card('hearts',1),
    ..., card('hearts',10), card('spades', 1), ..., card('spades', 10)]

我不知道从哪里开始。我有以下内容:

class card:
    'Fields: suit, value'
    def __init__(self, suit, value):
        self.suit = suit
        self.value = value
    def __repr__(self):
        return '{suit} {value}'.format(suit=self.suit,value=self.value)
  # A card is an object card(suit, value) where
  # * suit is one of 'clubs', 'spades', 'diamonds', 'hearts', and
  # * value is an integer in the range 1..10

def higher_in_rank(base_card):
    if base_card.suit == 'clubs':
        return     #clubs, diamonds, hearts, spades
    if base_card.suit == 'diamonds':
        return     #diamonds, hearts, spades
    if base_card.suit == 'hearts':
        return     #hearts, spades
    if base_card.suit == 'spades':
        return     #spades

我不知道如何为此创建代码。

2 个答案:

答案 0 :(得分:0)

我会使用他们的数字等级识别卡片,并从中得出套装和价值:

class Card(object):
    suits = ('clubs', 'diamonds', 'hearts', 'spades')
    values = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
    def __init__(self, rank):
        self.rank = rank
    def get_suit(self):
        return Card.suits[self.rank // 13]
    def get_value(self):
        return Card.values[self.rank % 13]
    def __str__(self):
        return '{suit} {value}'.format(suit=self.get_suit(),value=self.get_value())

def higher_in_rank(base_card):
    for rank in range(base_card.rank, 52):
        yield Card(rank)

base_card = Card(0 * 13 + 5)
for card in higher_in_rank(base_card):
    print card

答案 1 :(得分:0)

我会设置所有卡片的排序列表,然后通过查找给定卡片的索引并在其后返回列表中的所有内容,您可以快速获得比给定卡片更高的所有卡片。例如:

class card:
    'Fields: suit, value'
    def __init__(self, suit, value):
        self.suit = suit
        self.value = value
    def __repr__(self):
        return '{suit} {value}'.format(suit=self.suit,value=self.value)
    def __eq__(self, other):
        return (isinstance(other, self.__class__) and 
                self.suit == other.suit and self.value == other.value)

all_cards = [card(s, v) 
             for s in ('clubs', 'diamonds', 'hearts', 'spades')
                 for v in range(1, 11)]

def higher_in_rank(base_card):
    return all_cards[all_cards.index(base_card)+1:]

示例:

>>> higher_in_rank(card('spades', 8))
[spades 9, spades 10]
>>> higher_in_rank(card('diamonds', 6))
[diamonds 7, diamonds 8, diamonds 9, diamonds 10, hearts 1, hearts 2, hearts 3, hearts 4, hearts 5, hearts 6, hearts 7, hearts 8, hearts 9, hearts 10, spades 1, spades 2, spades 3, spades 4, spades 5, spades 6, spades 7, spades 8, spades 9, spades 10]