Session 4: Probability - Module E: Cards Program

1. Overview

Calculate card probabilities with a program.

2. Setting Up

Download cards.py:

  1. Download the Python program cards.py into your programs directory.

Start IPython:

  1. Open a terminal window.
  2. Change the directory to your programs directory with the cd command.
  3. Start IPython with the ipython command.
  4. From IPython, you can run your program by typing run cards.py.

3. Using the Cards Program

Now that you have seen how probabilities are calculated, let's use the cards program to do the work for us! First we need to create a new deck of cards:

deck = generateDeck()

The "cards" in this deck are counted when computing probabilities. In fact, if you made a custom deck, the reported probabilities would change too. Can you figure out how cards are represented in the deck? Hint: Open cards.py using gedit and review the code and console output.

To calculate probabilities, we will be using the function findProbability( ) which calls cardProbability( ) from macslib. The findProbability( ) function can be used to find and print the probability of drawing any sequence of one or more cards from a deck. When we call findProbability( ), we pass the deck, whether we want replacement, then one or more cards.

Here are some examples:

# probability of drawing an ace of spades
findProbability(deck, False, "ace:spades")


# probability of drawing any queen or any king
findProbability(deck, False, ("queen","king"))


# probability of drawing king, then a queen, then a jack
findProbability(deck, False, "king", "queen", "jack")


# probability of drawing a red card, then a two WITH replacement
findProbability(deck, True, "red", "2")

Next, find and examine the two calls to findProbability( ). Before you run the program again, calculate each probability by hand. Once you've done that, uncomment the function calls and rerun the program. Were your calculations correct?

Finally, add more probability calculations to the end of your program. Try to add some complex card sequences for more interesting probabilities! Consider comparing results with and without replacement.

When specifying cards, allowed numbers and faces are 'ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'even', 'odd', 'face', and 'any'. Allowed card suits are 'diamonds', 'hearts', 'spades', 'clubs', 'red', 'black', and 'any'. You can specify both a number/face and a suit for the same card using 'face:suit'. You can specify multiple desired cards for the same draw with a list or tuple of card specifiers such as ('2','king').

Take a screenshot of your output, and answer these questions on your webpage.