[Tutor] (no subject)

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 10 May 2001 04:01:35 -0700 (PDT)


On Thu, 10 May 2001, Steven Burr wrote:

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


The switching method can go horribly wrong if we make a slight mistake.  
*grin*

    http://mail.python.org/pipermail/edu-sig/2000-November/000771.html
    http://mail.python.org/pipermail/edu-sig/2000-November/000772.html
    http://mail.python.org/pipermail/edu-sig/2000-November/000784.html
    http://mail.python.org/pipermail/edu-sig/2000-November/000785.html
    http://mail.python.org/pipermail/edu-sig/2000-November/000786.html

... hmmm... in fact, most of November's edu-sig articles might be
interesting.

    http://mail.python.org/pipermail/edu-sig/2000-November/thread.html


Switching appears to use less memory than the card-pulling method because
it doesn't require making new lists or expanding old ones.  The
card-pulling, on the other hand, needs to shrink the deck and expand it
again.  

We can do some benchmarks by using the time.time() function.  time.time()
gives us back the number of seconds since the Epoch, so if we use it like
a stopwatch:

###
start = time.time()
## Do expensive operation
stop = time.time()
print "It took", start-stop, "econds to finish this operation."
###

we can empirically see how the two methods compare.


Hope this helps!