1

I'm trying to start using objects properly, I've built a deck of cards which is my object. I want to be able shuffle and deal cards from it. However I can't figure out how to get the shuffle method to work correctly or even if this is the best way to do it.

import itertools
import random
class Deck:
 '''Deck of cards to be used in a card game'''
 def __init__(self):
 self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
 self.suits = ['c', 'd', 'h', 's']
 self.cards = set(itertools.product(self.faces, self.suits))
 def shuffle(self):
 self.cards = random.shuffle(self.cards)
 def deal(self):
 card = self.cards.pop()
 return card[0] + card[1]

Usage;

deck = Deck()
deck.shuffle()
deck.deal()
asked Mar 14, 2019 at 14:18
3
  • 1
    Should be using list instead of set. Commented Mar 14, 2019 at 14:21
  • 3
    random.shuffle modifies a list in-place; it returns None, not the shuffled list. Commented Mar 14, 2019 at 14:24
  • 1
    List and shuffle in place works. Thanks guys Commented Mar 14, 2019 at 14:28

1 Answer 1

2

Sets are not ordered, you could use list() to obtain an ordered deck. Furthermore random.shuffle(l) acts directly on the list and returns None, so you are overwriting the list with None.

import itertools
import random
class Deck:
 '''Deck of cards to be used in a card game'''
 def __init__(self):
 self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
 self.suits = ['c', 'd', 'h', 's']
 self.cards = list(itertools.product(self.faces, self.suits)) # ordered deck
 # self.cards = set(itertools.product(self.faces, self.suits)) # unordered deck
 def shuffle(self):
 random.shuffle(self.cards)
 def deal(self):
 card = self.cards.pop()
 return card[0] + card[1]
answered Mar 14, 2019 at 14:25
Sign up to request clarification or add additional context in comments.

2 Comments

There's no need for set at all, as product isn't going to produce any duplicates that need to be removed.
it needs only one between list or set. It didn't need list(set( ... )), thanks for pointing it out

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.