[Tutor] Deal a Random Deck - Challenge

Scott Widney SWidney@ci.las-vegas.nv.us
Fri Jul 25 16:43:02 2003


> Here's an interesting problem a coworker (former mentor) uses 
> when hiring:
>  * Write an algorithm to deal out a set of "cards"
> 
> 
> So my challenge, then: Can anyone come up with an even faster solution
> than option 3?
> 

How about the batteries-included approach:

>>> import random, profile
>>> def deck3(size):
... 	d = [(random.random(), i) for i in range(size)]
... 	d.sort()
... 	return [d[i][1] for i in range(size)]
... 
>>> def deck4(size):
... 	d = [i for i in range(size)]
... 	random.shuffle(d)
... 	return d
... 
>>> profile.run('deck3(10000)')
         10003 function calls in 0.520 CPU seconds

>>> profile.run('deck4(10000)')
         10003 function calls in 0.405 CPU seconds

>>> profile.run('deck3(100000)')
         100003 function calls in 5.633 CPU seconds

>>> profile.run('deck4(100000)')
         100003 function calls in 4.043 CPU seconds


The performance of the Standard Library routines never fail to impress me.
Especially those that deal with number-crunching.


Are-you-listening-tim-one?-ly y'rs
Scott