0

我必须创建一个函数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

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

4

2 回答 2

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
于 2013-04-02T17:11:21.333 回答
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]
于 2013-04-02T17:17:07.327 回答