Chapter 08 Litvin Python
Chapter 08 Litvin Python
Programming
in Python
>>> Second Edition:
with Python 3
Maria Litvin
Phillips Academy, Andover, Massachusetts
Gary Litvin
Skylight Software, Inc.
Skylight Publishing
Andover, Massachusetts
Skylight Publishing
9 Bartlet Street, Suite 70
Andover, MA 01810
web:
e-mail:
http://www.skylit.com
[email protected]
[email protected]
1 2 3 4 5 6 7 8 9 10
15 14 13 12 11 10
8 Counting
8.1 Prologue
131
132
CHAPTER 8 ~ COUNTING
Example 1
How many two-digit positive integers are there?
Solution
We can choose the tens digit in 9 ways (1 through 9) and the units digit in 10 ways.
The answer is 910 = 90.
Example 2
A license plate has three digits followed by three letters. All combinations of digits
and letters are allowed. What is the total number of possible license plates?
Solution
There are 10 ways to choose the first digit, 10 for the second digit, and 10 for the
third digit. There are 26 ways to choose the first letter; same for the second letter and
the third letter. The answer is 101010262626 = 17,576,000.
Example 3
How many different values can be represented in one byte?
133
Solution
There are 2 ways to set the first bit, 2 ways to set the second bit, and so on. The
answer is 28 = 256 .
The multiplication rule explains how very large numbers can easily arise in
combinatorial problems or why it is so hard to win the lottery.
Example 4
How many ways are there to cover a whole 19 by 19 Go board with white and black
stones?
Solution
2361 more than 2 10120 , that is many times more than there are atoms in the
universe.
Exercises
1.
A combination lock has three wheels with the digits 0 through 9 on each
wheel. What is the total number of possible combinations? 3
2.
Ice cream comes in two sizes, three flavors, and with any one of five
toppings. In how many different ways can you order an ice cream?
3.
How many three-letter names are possible in Python, such that all letters are
in lower case, the middle letter is a vowel (a, e, i, o, u) and the other
two are consonants? 3
4.
5.
In how many ways can we split 10 different marbles between two kids?
Hint: see Question 4.
134
CHAPTER 8 ~ COUNTING
6.
What is the number of all possible subsets of a set of ten elements, including
the empty set and the whole set?
Hint: see Question 5.
7.
What is the number of all possible colors that can be shown on a computer
screen, if the graphics adapter generates a color using 16 bits for each of the
red, green, and blue components of the color? 3
8.
8.3 Permutations
The multiplication rule also applies when we want to count possible arrangements of
objects without repetition.
Example 1
In how many ways can a coach choose three players, a point guard, a shooting guard,
and a center, from a team of seven players?
Solution
If they came from three different teams, we could choose the first player in 7 ways,
the second player in 7 ways, and the third player in 7 ways. But here we cannot just
multiply 777 because all three players come from the same team. Once we have
chosen the first player, there are only 6 players left. So we can choose the second
player in 6 different ways. Once we have done that, there are only 5 players left, so
we can choose the third player in 5 different ways. The answer is 765.
Example 2
How many ways are there to seat 6 students in a classroom with 20 desks?
Solution
We can seat the first student at any one of the 20 desks, the second student at any one
of the remaining 19 desks, and so on. The answer is 201918171615 = 27,907,200.
8.3 ~ PERMUTATIONS
135
It is possible to arrive at the above result in a different way. Let P be the number of
permutations of n objects. Lets take n objects, call one of them x and set it aside.
There are Pn 1 permutations of the remaining n 1 objects. For each of these Pn 1
permutations, we can insert x at the beginning, between any two objects, or at the
end, thus creating n different permutations of n objects. So, from each of the Pn 1
permutations of n-1 objects, we now obtained n different permutations of n objects.
Therefore, Pn = nPn 1 . Also, P1 = 1 , because there is only one permutation of 1
object. It is now clear that Pn = n! . To complete the proof more formally we would
need to refer to mathematical induction, which is explained in Chapter 11.
Example 3
How many ways are there to put 5 different party hats on 5 people?
Solution
5! = 120.
Example 4
How many ways are there to arrange the cards in the deck of 52 cards?
Solution
52! = 80658175170943878571660636856403766975289505440883277824000000000000.
136
CHAPTER 8 ~ COUNTING
Exercises
1.
2.
How many five-letter words (strings of letters) do not have the same letter
twice in a row? Count any combination of letters as a word.
3.
How many ways are there to choose most likely to succeed, best athlete,
best dancer, best dressed, and class clown, a boy and a girl in each
category, in a graduating middle school class of 30 girls and 36 boys? The
same person cannot be chosen in two categories. 3
4.
5.
How many ways are there to seat 8 people in a row of 6 chairs, with two
people left out?
Hint: assign chairs to people, not people to chairs.
3
6.
How many pages will be required to print all possible permutations of letters
ABCDEFGHIJKL? Each permutation is printed on a separate line; 60
lines fit on a page.
7.
Her method is to try all possible substitutions of different digits for different
letters (excluding 0 for M and S, because a number cannot start with a 0).
If she takes one minute for each try (her addition skills are excellent) and
finds the answer after trying half of all possible substitutions, how long will
it take Amelia to solve the puzzle? 3
137
Two words are called anagrams of each other if they are made up of the
same letters used in a different order: for example, MANGO and AMONG.
Jesse decided to write a program that finds all anagrams of a given word by
generating all possible permutations of its letters and looking up each
permutation in a list of words (obtained in a file). If the program can
generate and look up 360 permutations per second, how long will it take it to
find all anagrams of BINARY? DECIMAL? What about
CONVERSATION? 3
Example 1
n teams are playing in a round-robin tournament; each team plays once with every
other team. How many games will be played?
Solution
There are n ways to choose the first team and (n 1) ways to choose the second team
for a game. That gives n(n 1) . However, this way we have counted each game
twice, because it doesnt matter which team is called first and which second. If
n(n 1)
we swap the two teams we get the same game. Therefore, the answer is
.
2
Example 2
How many words can we make from the letters A L A B A M A (assuming any
arrangement of letters is a word)?
138
CHAPTER 8 ~ COUNTING
Solution
If all seven letters were different, we would have 7654321 = 7! words. But the
four As are the same, so we get the same word when we permute them. We have
counted each arrangement of seven letters the number of times equal to the number
7!
of permutations of four As, that is 4! times. The answer is
= 5 6 7 = 210 .
4!
Example 3
There are five identical pairs of gloves in a drawer. If you pull out two gloves at
random, what are the odds that they will make a pair?
Solution
We can pull the first glove in 10 ways and the second glove in 9 ways. However, if
the order is not important, we have counted each possibility twice. So the total
10 9
= 45 . We can pull a left glove in 5
number of ways to choose two gloves is
2
ways and a right glove in 5 ways, so the number of ways to pull out a pair is
54
5 5 = 25 . The number of ways to pull out 2 left gloves is
= 10 . The same for
2
two right gloves. The number of ways to pull out two gloves that dont make a pair
is 10 + 10 = 20 . So the numbers match: 25 + 20 = 45 . The odds of getting a pair are
25 : 20 = 5 : 4 (we say, 5 to 4).
Example 4
How many ways are there to seat a teacher and six students at a round table?
Arrangements are considered the same as long as each person has the same left and
right neighbors.
139
Solution
We can say that there are 7! total arrangements and 7 ways to rotate the table, so the
7!
= 6! = 720 .
answer is equal to
7
Another solution may be obtained by sitting down the teacher anywhere at the table;
then there are 6! ways to arrange the students.
Exercises
1.
2.
Ice cream comes in two sizes, three flavors, and with any two of five
toppings. How many different orders are possible? 3
3.
4.
How many ways are there to seat a group of six at a rectangular dinner table?
The host and the hostess must sit at the short sides and the four guests two at
each of the longer sides. Arrangements are considered the same as long as
each guest has the same neighbors.
5.
In how many ways can we color the six faces of a cube in six different
colors? The cube can be rotated any way you want the colorings are
considered the same. 3
6.
An airline is planning three non-stop flights from the East Coast of the
United States to the Caribbean. The airline serves six major cities on the
East Coast and 12 different Caribbean islands. Two non-stop flights can go
to the same island, but they cannot originate at the same East Coast city.
How many different configurations of the three flights are possible? 3
7.
How many ways are there to place eight rooks on a chessboard so that none
of them threatens any other? A rook moves vertically or horizontally by any
number of squares. (The 64 squares on a chessboard are marked a1
through h8 and considered different; the eight rooks are considered
identical.) 3
140
CHAPTER 8 ~ COUNTING
8.5 Combinations
Combinations are selections of k elements from a given set of n elements (0 k n),
n
disregarding the order. This number is written and read n-choose-k.
k
n
k are important numbers in mathematics and they have many nice properties.
n n
First of all, notice that there is a kind of symmetry: =
. Indeed, to choose
k n k
n
k objects is the same as to set aside the remaining n k objects. Note that = 1 .
n
n
Mathematicians have agreed that = 1 , so the symmetry is complete.
0
Lets derive a formula (with factorials) for n-choose-k using the multiplication and
division rules. Suppose we choose k objects as follows: we first arrange all n objects
in line, then take the first k. The total number of arrangements is n!. However, if we
rearrange the first k objects and/or the remaining n k objects, we will end up with
the same selection. There are k! ways to rearrange the first k objects and (n k )!
ways to rearrange the remaining n k objects. So we have counted each selection
k !(n k )! times. Therefore,
n!
n (n 1) ... (n k + 1)
n
=
k =
k (k 1) ... 1
k !(n k )!
n
It is useful to remember the formulas for for k = 0 , 1, 2, and 3:
k
8.5 ~ COMBINATIONS
141
n
0 =1
n
1 = n
n n(n 1)
2 =
2
n n( n 1)(n 2)
3 =
6
Example 1
How many ways are there to split 4 different pencils between two children, so that
each gets two pencils?
Solution
We need to choose two pencils for the first child the second child gets the other
two.
4 4 3
=6.
2 =
2
Example 2
How many ways are there to choose 5 cards from a deck of 52 cards?
Solution
52 52 51 50 49 48
= 2,598,960 .
5 =
5 4 3 2 1
142
CHAPTER 8 ~ COUNTING
Example 3
How many different bit patterns in a byte have exactly three bits set?
Solution
8 8 7 6
= 56 .
3 =
3!
n!
n
n n
is a neat formula, and it confirms the symmetry =
k =
. It is
k !(n k )!
k n k
not practical for some computations, though, because factorials get very large
n
quickly. For computer programs, it is more convenient to rewrite as a product
k
of fractions:
n k +1
n n n 1
...
k =
1
k k 1
Exercises
1.
2.
3.
How many ways are there to order a pizza with three toppings out of five
possible toppings? 3
4
Write for k = 0, 1, 2, 3, 4.
k
Pat has 40 beads of which 35 are white and 5 are black. The beads are
identical, except for the color. How many different bracelets can Pat make
using all 40 beads? The ends of a bracelet are asymmetrical: one has a hook
and the other an eyelet. 3
4.
143
n
Write a Python function nChooseK that calculates and returns as an
k
int. The function should work for 0 k n .
Hint: use a float for the
product of fractions, then convert it into an int, using the built-in function
round. Rounding helps avoid tiny inaccuracies in computer arithmetic.
5.
How many ways are there to split 9 different stickers among three people,
three apiece? 3
6.
7.
How many ways are there to make a full house Poker hand from a deck of
52 cards? Full house is three cards of one rank and a pair of another
rank. 3
8.
Hint: see
n times
resulting polynomial?
9.
(( P Q) ( P Q)) (( P Q) P )
It has three and three operators. Suppose we reshuffle these six
operators to make new expressions. Show that among all different
expressions obtained this way, at least two will have the same truth tables.
Hint: dont do logic just count.
144
CHAPTER 8 ~ COUNTING
Example 1
How many ways are there to choose one or two ice cream toppings from five
available toppings?
Solution
One topping is not the same as two toppings! There are 5 ways to choose one and
54
= 10 ways to choose two. The answer is 5 + 10 = 15.
2
Example 2
How many ways are there to schedule two quizzes in a five-day week, if the quizzes
cannot be on the same day or on consecutive days?
Solution
If the first quiz is on the first day, the second quiz can be on the third, fourth or fifth
day three possibilities. If the first quiz is on the second day, the second quiz can
be on the fourth or fifth day 2 possibilities. If the first quiz is on the third day, the
second quiz must be on the fifth day 1 possibility. The answer is 3 + 2 + 1 = 6.
If you have trouble counting objects or arrangements that satisfy a certain condition,
you may try to count all possible arrangements, then count the arrangements that do
not satisfy the condition and subtract their number from the total.
Example 3
How many ways are there to seat two adults and four kids in a row in a movie theater
so that the two adults are not next to each other?
145
Solution
The total possible number of arrangements is 6! = 720. Lets count the number of
arrangements where the adults are sitting together. The number of ways to choose
two seats together for the adults is 5; the number of ways to seat the adults in these
seats is 2; the number of ways to seat the kids in the remaining four seats is 4!. So
the number of arrangements where the adults sit together is 52(4!) = 240. The
answer is 720 - 240 = 480.
Exercises
1.
How many different ways are there to make 50 cents using quarters, dimes,
and nickels? 3
3.
4.
Recall that a valid name in Python can consist of upper- and lowercase
letters, digits, and underscore characters, but cannot start with a digit. How
many valid Python names of length 3 or less are there? 3
5.
6.
Given cards 2 through 10 in four suits (36 cards total), how many ways are
there to make 21 on three cards? Hint: consider separately the cases where
all three cards have the same rank, two cards have the same rank, and all
three cards have different ranks. 3
146
CHAPTER 8 ~ COUNTING
7.
How many four-digit numbers have at least one 7 among their digits?
Hint: count the numbers that do not have any 7s. 3
8.
9.
10.
A password can contain upper- and lowercase letters as well as digits; it must
include at least one uppercase letter and at least one digit. How many
different four- or five-character passwords are possible? 3
8.7 Review
Terms and notation introduced in this chapter:
Combinatorics
Multiplication rule
Permutations
Factorial
Combinations
n-Choose-k
1 2 ... n = n!
n!
n
k =
k !(n k )!