Monday, February 15, 2010

Python: Shuffling A Deck Of Cards

Python continues to amaze me on a regular basis.

I love programming in Python. It's simple to read, the code is clean, it's testable, it's just plain a pleasant experience. And, quite frequently, something happens that just makes me go "wow".

If you've ever written code that needs to shuffle a deck of cards, you know that it can be annoying. It's not a difficult problem,. but it is one that you have to deal with on occasion.

You have a list of things, and you need them to now appear in a random order. One of the simplest ways to do it is to run a loop something like this (using Python):

unshuffled_list = [1,2,3,4,5,6,7,8,9,10]
shuffled_list = []
while len(unshuffled_list) > 0:
    r = random.randint(0,len(unshuffled_list)-1)
    del unshuffled_list[r]

shuffled_list will now contain a randomly ordered list consisting of the original contents of unshuffled_list.

Python, though, makes it much easier, and removes the possibility that you will introduce some small bug in your code. The way you should do it in Python?

shuffle_list = [1,2,3,4,5,6,7,8,9,10]

shuffle_list now contains the randomly ordered list. You're done.

It's a small thing. It's a simple thing. Some would even call it a silly thing. And yet, it makes life easier.

Thanks Python!

No comments: