Python Control Structures Exercises¶
Programming for Data Science Bootcamp
Exercise 1¶
What prints in the example below if val = 5
?
val = -2
if -10 < val < -5:
print('bucket 1')
elif -5 <= val < -2:
print('bucket 2')
elif val == -2:
print('bucket 3')
val = 5
if -10 < val < -5:
print('bucket 1')
elif -5 <= val < -2:
print('bucket 2')
elif val == -2:
print('bucket 3')
How would you fix the problem?
val = 5
if -10 < val < -5:
print('bucket 1')
elif -5 <= val < -2:
print('bucket 2')
elif val == -2:
print('bucket 3')
else:
print('bucket 4')
bucket 4
Exercise 2¶
Write code that does the following:
- Defines a list of integers
xx = [-2, 8, 0, 5, 6]
- Computes the maximum, storing in
max_val
- Loops over each value in the list
- If the value is less than the maximum, print the value
- Otherwise, print the string "max_val"
Method 1¶
xx = [-2, 8, 0, 5, 6]
max_val = max(xx)
for x in xx:
if x < max_val:
print(x)
else:
print('max_val')
-2 max_val 0 5 6
Method 2¶
for x in xx:
print(x) if x < max_val else print('max_val')
-2 max_val 0 5 6
Method 3¶
Jumping ahead to next week (Lambda λ functions)
_ = [(lambda x: print(x) if x < max_val else print('max_val'))(x) for x in xx]
-2 max_val 0 5 6
Exercise 3¶
Write code that does the following:
- Sets a variable
it
to $0$ - Sets a variable
max_iter
to $100$ - While
it
<max_iter
, does the following:- If
it
equals $0$ orit
is divisible by $10$, printit
. Hint: use modulo operator%
- If
- Increase
it
by $1$ - When
it
>=max_iter
, the program should quit
it = 0
max_iter = 100
while it < max_iter:
if (it == 0) or (it % 10 == 0):
print(it)
it += 1
0 10 20 30 40 50 60 70 80 90
Exercise 4¶
Create a list of four strings that are capitalized proper nouns.
Write a for
loop to iterate over the strings and:
- lowercase the string
- print the string
hint: Use the string method .lower()
.
names = ['John', 'Paul', 'George', 'Ringo']
for name in names:
print(name.lower())
john paul george ringo
_ = [print(x.lower()) for x in names]
john paul george ringo
Exercise 5¶
Using the list you made from the previous exercise, use iter()
and next()
to iterate over the list, printing each string.
The strings don't need to be lowercased.
beatles = iter(names)
print(next(beatles))
print(next(beatles))
print(next(beatles))
print(next(beatles))
John Paul George Ringo
for name in iter(beatles):
print(name)
beatles = iter(names)
_ = [print(next(beatles)) for i in range(len(names))]
John Paul George Ringo
Exercise 6¶
Create a dictionary with two city names as keys and their zip codes as values.
Use a for
loop with items()
to print each key-value pair.
city_zip = {
'Santa Barbara': 93103,
'Charlottesville': 22903
}
for city, zipcode in city_zip.items():
print(city, zipcode)
Santa Barbara 93103 Charlottesville 22903
_ = [print(city, zipcode) for city, zipcode in city_zip.items()]
Santa Barbara 93103 Charlottesville 22903
print("\n".join([f"{city} {zipcode}" for city, zipcode in city_zip.items()]))
Santa Barbara 93103 Charlottesville 22903
Exercise 7¶
Using the dictionary from the previous exercise, use a for
loop with keys()
to print each key-value pair.
To extract the values, use the key to index into the dictionary value.
city_zip = {
'Santa Barbara':93103,
'Charlottesville':22903
}
# for cit in city_zip.keys():
for city in city_zip:
print(city, city_zip[city])
Santa Barbara 93103 Charlottesville 22903
Exercise 8¶
Write a list comprehension that takes a list of numeric values
and returns a list of their cubes.
vals = [1, 2, 3, 4]
cubes = [val**3 for val in vals]
cubes
[1, 8, 27, 64]
Exercise 9¶
Create a list of seven $(7)$ strings that includes some numbers and some non-numbers.
The numbers should be quoted, like '12'
.
Write a list comprehension that takes the list and returns a list of the strings that are numbers.
Hint: The function isdigit()
will help.
strs = ['99', 'red balloons', 'floating', 'in the', 'summer sky.', '16', 'candles']
num_list = [st for st in strs if st.isdigit()]
num_list
['99', '16']
Without the function ...
numbers = list("1234567890")
num_list = []
for str in strs:
# Innocent until proven guilty
is_num = True
# Trial
for char in str:
if char not in numbers:
is_num = False
break
# Verdict
if is_num:
num_list.append(str)
print(num_list)
['99', '16']
Exercise 10¶
Given the dictionary grid
, use a comprehension to retain only key-value pairs where the key contains the substring 'max':
grid = {
'max_depth': [5,10],
'ntrees': [100,200,300],
'regularization': [11,12],
'max_iter': [10,20]
}
grid = {
'max_depth': [5,10],
'ntrees': [100,200,300],
'regularization': [11, 12],
'max_iter': [10,20]
}
grid_max = {key : grid[key] for key in grid.keys() if 'max' in key}
grid_max
{'max_depth': [5, 10], 'max_iter': [10, 20]}
Now create a dictionary with the same four keys but only the maximum values of each associated list.
new_grid = {}
for key in grid:
new_grid[key] = max(grid[key])
new_grid
{'max_depth': 10, 'ntrees': 300, 'regularization': 12, 'max_iter': 20}
new_grid = {key:max(grid[key]) for key in grid}
new_grid
{'max_depth': 10, 'ntrees': 300, 'regularization': 12, 'max_iter': 20}
Exercise 11¶
Given the dictionary letter_to_idx
which maps some letters to index values,
use a dictionary comprehension to create a reversed dictionary, idx_to_letter
mapping the index values to the letters.
letter_to_idx = {
'a': 0,
'b': 1,
'c': 2
}
letter_to_idx = {
'a': 0,
'b': 1,
'c': 2
}
idx_to_letter = {letter_to_idx[k]:k for k in letter_to_idx.keys()}
idx_to_letter
{0: 'a', 1: 'b', 2: 'c'}
Or try this:
idx_to_letter2 = {v:k for k, v in letter_to_idx.items()}
idx_to_letter2
{0: 'a', 1: 'b', 2: 'c'}