[Tutor] Shut up and deal!

Greg Lindstrom tubaranger at gmail.com
Mon Aug 8 18:04:19 CEST 2005


I found the conversation of dealing cards interesting, so I took a few 
minutes (about 20 while I waited for a production run to finish) and came up 
with the following Dealer class. I come with a long history of coding in 
C/C++ and have been told my code looks like it (notice, in particular the 
nested "for" loops in the Shuffle method). What type of Pythonic changes 
would make this? What features would be nice? This was just for fun, so 
let's not take it too seriously!

--greg

- - - - Start Snippet - - - - - - - - - -
#!/usr/bin/python
from random import shuffle

class Dealer(object):
# define your deck here
SUITS = ('Spades', 'Hearts', 'Clubs', 'Diamonds')
RANKS = ('2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace')

def __init__(self, decks=1, suits=SUITS, ranks=RANKS):
self.number_of_decks = decks
self.suits = suits
self.ranks = ranks
self.Shuffle()

def Shuffle(self):
self.deck = []
for deck in range(self.number_of_decks):
for suit in self.suits:
for rank in self.ranks:
self.deck.append('%s of %s'%(rank,suit))
shuffle(self.deck)

def Deal(self):
'''Return the top card from the deck, or None if the deck is depleated'''
if len(self.deck) > 0:
card = self.deck[0]
del self.deck[0]
return card
else:
return None

###############################################################################
### Unit Test 
#################################################################
###############################################################################
if __name__ == '__main__':
dealer = Dealer()
for n in range(10):
print dealer.Deal()

- - - - End Snippet - - - - -

Which yields:
2 of Clubs
7 of Diamonds
9 of Diamonds
Ace of Diamonds
Jack of Hearts
King of Hearts
8 of Clubs 
King of Clubs
5 of Spades
3 of Hearts
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050808/348e960a/attachment-0001.htm


More information about the Tutor mailing list