0

So, I've got the basic deck of cards, but I am having trouble with the printing process. My professor is having us use the eq and str method, hence the reason I used that in my code. Any suggestions for where I am going wrong? How do I change the main section to convert each card in a returned hand to a string and only print it then?

import random
class Deck(object):
        """Represent a deck of 52 playing cards."""

        def __init__(self, start_shuffled):
            """Initializes a deck with 52 cards."""
            suits=["H","S","D","C"]
            ranks= list ( range(2, 11)) + ["J", "Q", "K", "A"]
            self.cards=[]
            for suit in suits:
                    for rank in ranks:
                            self.cards.append(Card(suit, rank))
            if start_shuffled:
                    random.shuffle(self.cards)
        def __str__(self):
                res = []
                for card in self.cards:
                    res.append(str(card))
                return '\n'.join(res)

        def has_card(self, card):
            return card in self.cards

        def draw_random_card(self):
            card=random.choice(self.cards)
            self.cards.remove(card)
            return card
        def draw_hand(self, num_cards):
            cards=[ ]
            for _ in range(num_cards):
                    cards.append(self.draw_random_card())
                    return cards
class Card(object) :
        def __init__(self, s , r):
            self.suit=s
            self.rank=r

        def __str__(self):
                rep = self.rank + self.suit
                return rep
        def __eq__(self, other_card):
                t1 = self.suit, self.rank
                t2 = other_card.suit, other_card.rank
                return eq(t1, t2)

def main():
        deck1=Deck(True)

        print("All the cards in the deck:")
        print(deck1.cards)
        print("Does the deck have the Queen of Hearts? True or False")
        print(deck1.has_card(Card("H", "Q")))
        card=deck1.draw_random_card()
        print("A random card from the deck:")
        print(card)
        if deck1.has_card(card):
                print("Something bad happened...")
                print(card, "Shouldn't be in the deck anymore.")
        print("A hand of six random cards:")
        print (deck1.draw_hand(6))


if __name__=="__main__":
        main()

2 Answers2

2

You're getting a NameError on this line:

return eq(t1, t2)

Because there's no such function, eq. Just use the equality operator.

return t1 == t2

Then, you're getting a TypeError on this line:

rep = self.rank + self.suit

Because sometimes rank is an integer, and you can't add an integer and a string together. Convert rank to a string before concatenating.

rep = str(self.rank) + self.suit

Then, when you print the whole deck, it shows something like <__main__.Card object at 0x00000000024A19E8>, because objects don't use __str__ when you print them inside a collection. Implement a __repr__ method for your cards.

    def __repr__(self):
        return self.__str__()

Now you should be getting nicer output.

All the cards in the deck:
[10H, QS, 9D, 10C, 5S, AS, 5C, 10D, AC, 9C, 3H, 3D, 
6H, JH, AD, 7D, KC, 7H, JD, 9H, 8H, 3C, 3S, 4H, 8C, 
QD, 6C, 9S, QC, 6D, JS, 7S, 5H, 10S, KH, 2C, 7C, JC, 
6S, 4D, 4S, 5D, 4C, AH, 2S, 8S, 8D, KS, 2D, KD, 2H, QH]
Does the deck have the Queen of Hearts? True or False
True
A random card from the deck:
3H
A hand of six random cards:
[3D]
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • When you say "eq", do you mean "eq" and are using bold for emphasis? Or do you mean `__eq__`, but the markdown system is misinterpreting your underscores? If it's the latter, you are still using `__eq__`, and `__str__`, so it satisfies your assignment's requirements. – Kevin Apr 17 '14 at 17:19
  • Using str is still possible. If you're being forced to use eq directly, I believe that is still possible, but you'll need to use it slightly differently. Something like `self.__eq__(othercard)` when you make a call to it. But I'd also confirm that, because that sounds like an odd thing to ask someone to do. – K.Niemczyk Apr 17 '14 at 17:20
1

Couple things:

  1. Check your indentation on draw_hand. You're never putting more than one card in the hand to return.
  2. Change __str__ to __repr__. I did this and it starting printing out fairly normally for me. There is a good discussion on the difference between__str__ and __repr__ here
  3. There are a few other compile type issues, such as a direct called to __eq__, but Kevin already addressed those.
Community
  • 1
  • 1
K.Niemczyk
  • 1,130
  • 3
  • 12
  • 26