Greg Lindstrom wrote:
> 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!

It looks pretty good to me; a couple of alternatives suggested below. Oh, and 
typical Python usage is to start method names with lower case letters, e.g. 
shuffle(), deal().

Kent

> 
> --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))

If you don't like the nested for you can use a generator expression with two 
'for' clauses:
  deck.extend('%s of %s'%(rank,suit) for suit in self.suits for rank in 
self.ranks)
though I think your version is clearer.


>        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

could be
  try:
    return self.deck.pop(0)
  except IndexError:
    return None

Since you don't really care which end of the deck is dealt you could pop the 
end of the deck (use self.deck.pop()), that avoids having to move all the other 
cards down.

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

Reply via email to