Skip to content

Instantly share code, notes, and snippets.

@kshitij10496
Last active August 28, 2017 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kshitij10496/1aa0fed94b1aaba6165a73220f5fe77a to your computer and use it in GitHub Desktop.
Save kshitij10496/1aa0fed94b1aaba6165a73220f5fe77a to your computer and use it in GitHub Desktop.
Sample Implementation of a Deck class to represent the utility of Iterator Protocol
from collections import namedtuple
import random
Card = namedtuple('Card', ['rank', 'suit'])
class Deck(object):
'''Represents an ordered deck of 52 playing cards.'''
def __init__(self, cards=None):
if cards is None:
cards = shuffle_pack()
self.cards = cards
def __repr__(self):
cards_repr = ''
for card in self.cards:
cards_repr += repr(card) + '\n'
return 'Deck(cards={})'.format(cards_repr)
def __iter__(self):
'''Generator function.'''
for card in self.cards:
yield card
def shuffle_pack():
'''Utility function to shuffle a pack of cards.'''
suit_mapping = {0: 'Spades', 1: 'Hearts', 2: 'Clubs', 3: 'Diamonds'}
ranks = range(52)
ordered_cards = random.sample(ranks, 52)
deck = list()
for card in ordered_cards:
suit, rank = suit_mapping[card//13], (card % 13) + 2
c = Card(rank, suit)
deck.append(c)
return deck
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment