Exercises for Lesson 11
Exercise 1: Compound Boolean expressions
Evaluate the following expressions.
x = 4
y = 2
(a) x > 0 and y < 5
(b) x == 4 and False
(c) (not x == 3) and (not y <= 2)
(d) x == 0 or (x > 1 and y != 14)
Exercise 2: Truth tables
Write truth tables for the following expressions.
(a) a and (not b)
(b) (a and b) or (not a and not b)
(c) not (a and b)
Exercise 3: Truth tables, revisited
Part a: more truth tables
Write truth tables for the following expressions.
(a) a and (not b or a)
(b) (a or b) and (not a or b)
(c) not (a or (b and a))
Part b: simplification via truth table
Use your truth tables from Part a to verify the following simplified expressions are equivalent to the original expressions.
(a) a
(b) b
(c) not a
Exercise 4: A simple while loop
Write a function that uses a while
loop to build a list of negative numbers the user enters, until they type 0
.
def keepNegatives():
"""
Asks the user to enter integers, and keeps track of negative numbers entered.
Stops once the user inputs `0`.
returns: the negative numbers entered (a list of ints)
"""
return [] # replace with your code
Exercise 5: Dividing by 2
Write a function that takes a value n
and returns the number of times that n
can be divided by 2 (using integer division) before reaching 1. Your function should use a while
loop.
def numberTimesDivisible(n):
"""
Returns the number of times n can be divided by 2
(integer division) before reaching 1.
Assumes n is at least 1.
ex: n=1 -> 0
n=2 -> 1
n=3 -> 1
n=4 -> 2
"""
return -1 # replace with your code
Exercise 6: More practice with while
The greatest common divisor (GCD) of two values can be computed using Euclid’s algorithm. Starting with the values m
and n
, we repeatedly apply the formula: n, m = m, n % m
, until m
is 0. Then, n
is the GCD of the original values of m
and n
.
Write a function that finds the GCD of two numbers using this algorithm.
Hint: You should use the formula from above as a line of code in the loop; if you don’t use “simultaneous assignment” of two variables at once, you’ll need a temp variable to avoid losing the value of n
after updating it via n = m
.
def gcd(m, n):
"""
Calculates the GCD of m and n using Euclid's algorithm.
Process:
* n = m
* m = n % m (note this must be simultaneous)
* continue until m is 0, then the result is in n
"""
return -1 # replace with your code