创建一个消耗卡片列表的函数,并生成红色和奇数卡片的列表

时间:2013-04-02 16:41:58

标签: python class

我必须写一个函数red_odd,它会消耗一张牌,手牌,然后按顺序生成一张红色牌(即“钻石”或“心脏”)并有奇数值的牌子列表它们出现在消费列表中。消费列表不能变异。

例如,

red_odd([card1,card2,card3,card4])=> [card2]

所以到目前为止我有这个:

class card:
    'Fields: suit, value'
    def __init__(self, suit, value):
        self.suit = suit
        self.value = value

card1 = card('spades', 8) 
card2 = card('hearts', 5) 
card3 = card('diamonds', 6) 
card4 = card('clubs', 5)

def red_odd(hand):
    card_list = []
    for c in hand:
        if (c.suit == 'diamonds' or c.suit == 'hearts')  and (c.value / 2 != 0):
            card_list.append(c)
    return card_list

它没有运行,我不确定我哪里出错了。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您只需要调用您的函数:

odd_red_cards = red_odd([card1,card2,card3,card4])
print(odd_red_cards)

这会给你一些调试。


请注意,添加__str____repr__功能可能会非常有用,可让您的卡片更自然地打印,这对于查找其他错误非常有用。 e.g:

class card(object):
     ...
     def __repr__(self):
         return '{suit} {value}'.format(suit=self.suit,value=self.value)