-1

Create a class Deck that represents a deck of cards. Your class should have the following methods:

  • constructor: creates a new deck of 52 cards in standard order.
  • shuffle: randomnizes the order of the cards.
  • dealCard: returns a single card from the top of the deck and removes the card from the deck
  • cardsLeft: returns the number of cards remaining in the deck.

Test your program by having it deal out a sequence of n cards from a shuffle deck where n is the user input.

class Deck:

    def __init__(self):
        self.cardList=[]
        for suit in ["d","c","h","s"]:
            for rank in range(1,14):
                card=PlayingCard(suit, rank)
                self.cardList.append(card)
    def shuffle(self):
    #I DON'T KNOW HOW TO SHUFFLE MY CARDS PLEASE HELP.
    #self.cardList[pos1] = self.cardList[pos2]
    #self.cardList[pos2] = self.cardList[pos1]
    #these two lines above are not working
    def dealCard(self):
        return self.cardList.pop() 

    def cardsLeft(self):
        return len(self.cardList)
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Jess
  • 3
  • 2

1 Answers1

1

Read the docs on random.shuffle. It should help you greatly! :)

from collections import namedtuple
from random import shuffle

PlayingCard = namedtuple('PlayingCard', "suit rank")

class Deck:

    def __init__(self):
    self.cardList = [PlayingCard(suit, rank) for suit in"dchs" for rank in range(1,14)]

    def shuffle(self):
        shuffle(self.cardList)

    def dealCard(self):
        return self.cardList.pop() 

    def cardsLeft(self):
        return len(self.cardList)

d = Deck()
d.shuffle()
print [d.dealCard() for _ in range(5)]
Maria Zverina
  • 10,863
  • 3
  • 44
  • 61