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



_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to