[Tutor] (no subject)

Steven Burr sburr@home.com
Thu, 10 May 2001 00:38:49 -0700


The discussion on the random.shuffle() function reminded me of a 
question I had about shuffling.  As an exercise, I've been
working on a module containing classes that could be used in text-based 
card games.   In my "Deck" class (which inherits from "Cards," which 
inherits from "UserList"), I included the following shuffle method:

	def shuffle(self):
      		d = []
      		for i in range(len(self) - 1, -1, -1):
      			d.append(self.pop(self.index(random.choice(self.data))))
      		self.data = d

In effect, the method popped random cards out of a list of cards and 
appended them to a new list until the original list was exhausted.  The 
new list then replaced the old in the Cards object.  It seemed to work 
fine.

I later read a tutorial that included a card game example (How to Think 
Like a Computer Scientist, Java version).  The shuffle method in the 
example switched each card in the array with another randomly chosen 
card from the same array.  When the Python random.shuffle function was 
mentioned, I took a look at the module, apparently written by the BDFL, 
and saw that Guido used essentially the same switching method (although 
it looks a lot better in Python than in Java : ).   Naturally, I 
promptly rewrote my shuffle method:

	def shuffle(self):  random.shuffle(self.data)

Still I'm curious.  Is there a clear advantage to the switching method 
as opposed to the pop and append method?