It takes some mathematical insight to figure out how many elements satisfy a property without enumerating all of them. Here are some standard techniques.
The Sum Rule: If there are n(P) ways to do P and, distinct from them, n(Q) ways to do Q, then the number of ways to do P or Q is n(P) + n(Q). For example, you have decided to go either to the movies or to the mall tonight. If you go to the multiplex, you can watch one of five movies. If you go to the mall, you could shop at the furniture store or the cloth store. As per the sum rule, you have a choice of seven different things for tonight (5 + 2).
The Product Rule: If there are n(P) ways to do P and n(Q) independent ways to do Q, then the number of ways to do P and Q is n(P) * n(Q). This is what we already saw as the basic counting principle. For example, you decide to order pizza. You have two choices of crust: thin or deep dish. Next, you have to choose one of the four toppings: olives, cheese, mushroom, or peppers. In how many ways can you order your pizza? You are choosing a crust and a topping. The word and usually indicates the product rule. The answer is 2 * 4 = 8 ways.
Your school will award a free calculator to either a Math student or a Math professor. How many different choices are there if there are 55 students and six professors? The question says either student or professor. The word or is usually associated with the sum rule. There are 55 + 6 = 61 choices.
Python, with its built in functions and data structures, can make counting very easy, even by enumeration!
Let’s use the Python
set to solve our outfit problem. Write the code to loop through the given two sets - Shirt, Jeans - to display all possible outfits.
A counter variable,
count, has been initialized to
count in the nested loop and print the final
count at the end of the program.