Escolar Documentos
Profissional Documentos
Cultura Documentos
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
sales@skylit.com
support@skylit.com
1 2 3 4 5 6 7 8 9 10
15 14 13 12 11 10
6 Boolean Algebra
6.1 Prologue
A proposition is a statement that is either true or false. For example: Henry likes
macaroni, or 100 is a prime. Formal logic deals with the laws of reasoning that
apply to propositions. Logical operations on propositions are not unlike arithmetic
operations on numbers. In arithmetic, we can express common properties of
operations using algebraic notation. For example, take the distributive law for
multiplication:
a(b + c) = ab + ac
Similarly, we can use the notation of Boolean algebra to express general laws of
logic. For example:
not (A and B) (not A) or (not B)
P Q means P is equivalent to Q or P is true if and only if Q is true. The
above law says, for example: not (rich and famous) is true if and only if (not rich) or
(not famous) is true. Formal logic is not very difficult: most of it is common sense.
There is a special notation for logical operations: means not, means and,
means or. In this notation, the above formula would look like this:
( P Q ) ( P ) ( Q )
However, we will continue using and, or, not for the sake of simplicity.
Boolean algebra is named after the British mathematician George Boole (18151864), who described the laws of logic in his books The Mathematical Analysis of
Logic and The Laws of Thought.
95
96
Q
T
F
T
F
P and Q
T
F
F
F
A table of this kind is called a truth table. It shows the values of a logical expression
(here P and Q) for all possible combinations of values of variables.
97
Q
T
F
T
F
P or Q
T
T
T
F
not P
F
T
In English, the words and, or, not can be used differently in different contexts.
For example, a statement Henry likes macaroni and cheese most likely means that
Henry likes macaroni with cheese, not that he likes macaroni and also likes cheese.
In English, or is more often used as exclusive or: P or Q, but not both. For
example: Live free or die means do one or the other, but not both. In Boolean
algebra the operations and, or, and not have precise meanings, as described above.
Table 6-1 lists some of the important laws of logic. Note the duality of the laws: if
you take a law of logic and replace each and with or and each or with and, you get
another valid law of logic. (In Table 6-1, dual laws are written in the same block.)
Of all the laws in the table, De Morgans laws are the least obvious; these laws are
very useful in computer programming. We gave an example of one in the prologue.
98
not (not P) P
P or (not P) T
P and (not P) F
Law of contradiction
P and Q Q and P
P or Q Q or P
Commutative laws
Distributive laws
P or (Q and R) (P or Q) and (P or R)
not (P and Q) (not P) or (not Q)
not (P or Q) (not P) and (not Q)
De Morgans laws
Exercises
1.
2.
3.
4.
5.
6.
Make a truth table for the expression P and (Q or R). Hint: your table
needs all possible combinations of T/F values for P, Q, and R, so it will have
8 rows.
99
8.
Write a logical expression with two variables, P and Q, that has the
following truth table:
P
T
T
F
F
Q
T
F
T
F
?
F
T
T
F
x A p( x) = True
(x is an element of A if and only if p ( x) is true)
We will call A the truth set of p (Figure 6-1).
100
Domain of the
predicate p
U
A
True
Truth set
of p
False
Figure 6-1. The truth set of a predicate
Example 1
Suppose U is the set of all real numbers: U = \ . The predicate p is defined as
follows: p ( x) is true if x 1 ; false otherwise. The truth set of p is the subset of all
Example 2
U is a set of all integers: U = Z . Describe a predicate that corresponds to the subset
of all positive integers that are divisible by 3.
Solution
True, if n > 0 and n mod 3 = 0 (n is divisible by 3)
p ( n) =
False otherwise
101
B
A
A B
UA
A B
Example 3
Let U be a set of all integers: U = Z . Describe the predicate n is a positive integer
that is divisible by 3 as a conjunction of two predicates. Mark on the number line
the truth set for each of them and the intersection of these sets.
Solution
n greater than 0 and n is divisible by 3.
-3
-2
-1
102
If p and q are two predicates, we can consider a new predicate: their disjunction:
p or q. ( p or q)( x) is true if and only if p ( x) or q( x) or both are true. The truth
set of (p or q) is the union of the truth set of p and the truth set of q. The union of
two sets A and B is denoted by A B (Figure 6-2).
The union of two sets A and B is the set of all the elements that belong to
A or B (or both).
Finally, for any predicate p we can consider a new predicate, the negation of p, not p.
If A is the truth set of p, then the truth set of its negation is U A , that is all the
elements of U that are not in A. U A is called the complement of A (in U). Once
we agree on the universal set U, we can denote the complement of A in U simply
as A .
Example 4
Suppose we toss a coin three times and record the result as a sequence of three digits,
using 0 for heads and 1 for tails. Let U be the set of all possible outcomes:
{000, 001, 010, 011, 100, 101, 110, 111}. What is the truth set of the predicate
there were two tails in a row? Now describe the negation of this predicate and its
truth set.
Solution
The truth set of there were two tails in a row is {011, 110, 111}. The negation of
there were two tails in a row is there were not two tails in a row. Its truth set is
{000, 001, 010, 100, 101}.
Operation on
predicates:
Formal
notation:
Operation on sets:
p and q
pq
Ap Aq
103
p or q
pq
Ap Aq
(the union of Ap and Aq )
not p
Ap
(the complement of Ap )
Example 5
One of the two De Morgans laws is ( P Q) (P) (Q) . The corresponding
law for sets is A B = A B .
Exercises
1.
Some students take drama. Some take chorus. Some take band. Some take
two of the above. Some take all three. Draw a Venn diagram that illustrates
this situation.
2.
3.
Sketch a set of all points (x, y) on the x-y plane such that
x 0, y 0, and x 2 + y 2 1 .
4.
Sketch a set of all points (x, y) on the x-y plane such that ( x 2)( y 1) 0 .
104
5.
In a Sudoku puzzle, the objective is to fill a 9-by-9 grid with digits from 1 to
9 in such a way that each row, each column, and each of the nine 3-by-3
squares hold all the digits 1 through 9. The grid below shows a configuration
of 1s and 2s on a Sudoku grid.
1
2
1
2
2
Mark all the remaining squares on the grid where both 1 and 2 are possible
candidates.
6.
7.
Suppose two predicates p and q (on the same set) are such that if p ( x) is true
then q( x) is true. In this case we say that p implies q and write p q .
Describe the relationship between the truth sets of such predicates. 3
8.
Translate the laws of logic from Table 6-1 into the corresponding laws for
sets.
9.
105
Programs often need to decide how to proceed based on a certain condition. CPUs
have special conditional jump instructions that either continue with the next
instruction or jump to a different place in the program, depending on the result of the
previous operation (see the example in Section 2.2). High-level languages have
if-else statements for conditional branching.
Example 1
This statement works as follows: if s is not empty and the first character in s is '-',
then sign gets the value -1; otherwise sign gets the value 1.
If the condition is true, the statements indented under if are executed; otherwise the
statements indented under else are executed. After that, the program proceeds with
the statement that follows if-else. Dont forget the colons!
106
The else clause is optional: you can have if alone. In that case, if the condition is
true, the program executes the statements indented under if; otherwise, the program
skips them.
Example 2
if with no else
if x < 0:
x = -x
...
If you want to do nothing under if and something under else, you can use
Pythons do nothing statement, pass.
Example 3
Copyright 2008-2010 by Skylight Publishing
if with pass
if y == 0:
pass
# do nothing
else:
print(1/y)
...
Often you need to chain several if-else statements together. For example:
def letterGrade(score):
if score >= 90:
return 'A'
else:
if score >= 80:
return 'B'
else:
if score >= 70:
return 'C'
else:
if score >= 60:
return 'D'
else:
return 'F'
107
Python lets you simplify the indentation and compress the else-if on one line, using
the keyword elif. The above code can be shortened to:
def letterGrade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
Python has two special built-in constants: True and False. A condition is a
Boolean expression that evaluates to True or False. So a condition is basically a
predicate on the values of the variables involved. We have already encountered
conditions when we talked about while loops, in Chapter 4.
Conditions are written using relational operators and logical operators. Python has
the following relational operators:
Operator
==
!=
<
<=
>
>=
Description
equal
not equal
less than
less than or equal to
greater than
greater than or equal to
108
Python has one more relational operator, in, which works with sequences (strings,
lists, tuples, etc). x in s returns True if x is a character or a substring in the string
s, or if x is an element in the list or tuple s. If x is not a member of s, in returns
False. For example:
>>> 'a' in 'abc'
True
>>> 'b' in 'abc'
True
>>> 'bc' in 'abcd'
True
>>> 'cb' in 'abcd'
False
>>> 3 in [1,2,3]
True
>>> 2 in (1,2,3)
True
>>> [2,3] in [1,2,3]
False
The latter expression evaluates to False because the in operator does not work for
slices of lists (sublists), only for single elements. [2,3] in [1,[2,3]] would
give True.
You can also use the not in operator. x not in s is sometimes more readable
than not (x in s).
Example 4
Suppose name is a string and guests is a list. Write a code segment that checks
whether name is in the list guests, and if so, prints Welcome, followed by name.
If name is not in guests, the code should print May I help you?
109
Solution
if name in guests:
print('Welcome, ' + name)
else:
print('May I help you?')
Conditions can also include calls to Boolean functions. (By Boolean function, we
just mean a function that can return only True or False.) Python has a small
number of built-in Boolean functions, and you can write your own.
Example 5
110
Example 6
def greaterThan(a, b):
if a > b:
return True
else:
return False
For
if s is an empty string, len(s) == 0, and the code will set sign to 1. But if we
write
111
an empty string will raise a string index out of range exception, because the
character s[0] does not exist.
Exercises
1.
2.
3.
(not a) or (not b)
(not a) or b
(not a) and b
4.
Write a function that returns the number of days in a given month, specified
by name: 'January', 'February', and so on. Use an if-elif-else
sequence. 3
5.
6.
Using the function isPrime from Example 5, write a program that prints all
the prime numbers under 1000.
7.
Write a Boolean expression in Python that is true if and only if the string s
contains either a '+' or a '-', but not both. 3
112
8.
3
9.
10.
Write a program that plays Rock-Paper-Scissors with the user and displays
the cumulative score. For example:
Rock... Paper... Scissors... Shoot!
Make your move (r, p, s) or q (to quit): s
I said Rock
Ha! You are zapped 1:0
Rock... Paper... Scissors... Shoot!
Make your move (r, p, s) or q (to quit): p
I said Paper
Paperaper! Tie 1:0
Rock... Paper... Scissors... Shoot!
Make your move (r, p, s) or q (to quit): q
Sorry, you lost! 1:0
Thanks for playing.
Hints:
1. The call choice(s) returns a randomly chosen character from the string
s (or a randomly chosen element from the list or tuple s.). The function
choice is in the module random, so you need
from random import choice
2. Recall that raw_input(prompt) prompts the user for input and returns
the entered string.
6.5 ~ REVIEW
11.
12.
6.5 Review
Terms and notation introduced in this chapter:
113
Proposition
Conjunction
Disjunction
Negation
Boolean algebra
And operation
Or operation
Not operation
Truth table
De Morgans laws
Predicate
Truth set
Intersection of sets
Union of sets
Complement set
Venn diagram
Relational operators
Logical operators
114
return True
return False
return < Boolean expression >