View Single Post
Old Oct 31st, 2005, 7:58 AM   #4
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
The first thing I'd do to shorten it would be to use list comprehensions:
import random

# (By convention, classes should ideally have their first letter capitalised)
class Cards:
   def __init__(self):
      suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
      numbers = ["Ace"] + range(2, 11) + ["Jack", "Queen", "King"] 
      self.pack = ["%s of %s" % (n, s) for n in numbers for s in suits]
      self.shuffle()
The second thing would be to use random.shuffle to shuffle my cards:
   def shuffle(self):
      random.shuffle(self.pack)
Because I'm shuffling the cards, rather than indexes to the cards, I can shorten draw_a_card, too:
   def draw_a_card(self):
      card = random.choice(self.pack)
      self.pack.remove(card)
      return card
In fact, we can shorted draw_a_card further. In real life, the dealer shuffles, then (usually) deals off the top. Assuming our shuffling is random enough, we can cut this function to:
   def draw_a_card(self):
      return self.pack.pop()
Using list comprehensions, we can cut deal() to one line:
   def deal(self, number_of_cards):
      print "Your hand: %s" % [self.draw_a_card() for i in range(number_of_cards)]
Indeed, we can do away with draw_a_card now, if we wish:
   def deal(self, number_of_cards):
      print "Your hand: %s" % [self.pack.pop() for i in range(number_of_cards)]

So, assuming we're not too fussed about shuffling more than once, and assuming we're not worried about exceptions occuring when running out of cards (as in the original code), we can cut the program down to 20 lines:
#! /usr/bin/python
# Card Dealer

import random

class Cards:
   def __init__(self):
      suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
      numbers = ["Ace"] + range(2, 11) + ["Jack", "Queen", "King"]
      self.pack = ["%s of %s" % (n, s) for n in numbers for s in suits]
      random.shuffle(self.pack)
      
   def deal(self, number_of_cards):
      print "Your hand: %s" % [self.pack.pop() for i in range(number_of_cards)]
   
newgame = Cards()
deal = "y"
while deal == "y":
   newgame.deal(5)
   deal = raw_input("Deal again? (y/n)")
Arevos is offline   Reply With Quote