Exercises for Lesson 10
Exercise 1: 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.
Hint: Recall that you can use mylist.append(x) to add a new element x to the end of list mylist.
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 codeExercise 2: 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 3: 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