M03 Exercises¶

Example 3.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')

How would you fix the problem?

In [124]:
val = 5

if -10 < val < -5:
    print('bucket 1')
elif -5 <= val < -2:
    print('bucket   2')
elif val == -2:
    print('bucket 3')
In [2]:
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 3.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¶

In [4]:
xx = [-2, 8, 0, 5, 6]
In [5]:
max_val = max(xx)
In [6]:
for x in xx:
    if x < max_val:
        print(x)
    else:
        print('max_val')
-2
max_val
0
5
6

Method 2¶

In [7]:
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)

In [9]:
_ = [(lambda x: print(x) if x < max_val else print('max_val'))(x) for x in xx]
-2
max_val
0
5
6

Example 3.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$ or it is divisible by $10$, print it. Hint: use modulo operator %
  • Increase it by $1$
  • When it >= max_iter, the program should quit
In [ ]:
it = 0
max_iter = 100
while it < max_iter:
    if (it == 0) or (it % 10 == 0):
        print(it)
    it += 1

Exercise 3.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().

In [15]:
names = ['John', 'Paul', 'George', 'Ringo']
In [16]:
for name in names:
    print(name.lower())
john
paul
george
ringo
In [126]:
_ = [print(x.lower()) for x in names]
john
paul
george
ringo

Exercise 3.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.

In [127]:
beatles = iter(names)
print(next(beatles))
print(next(beatles))
print(next(beatles))
print(next(beatles))
John
Paul
George
Ringo
In [49]:
beatles = iter(names)
for name in iter(beatles):
    print(name)
John
Paul
George
Ringo
In [46]:
beatles = iter(names)
_ = [print(next(beatles)) for i in range(len(names))]
John
Paul
George
Ringo

Exercise 3.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.

In [130]:
city_zip = {
    'Santa Barbara': 93103, 
    'Charlottesville': 22903
}

for cit, zi in city_zip.items():
    print(cit, zi)
Santa Barbara 93103
Charlottesville 22903
In [54]:
_ = [print(cit, zi) for cit, zi in city_zip.items()]
Santa Barbara 93103
Charlottesville 22903
In [55]:
print("\n".join([f"{cit} {zi}" for cit, zi in city_zip.items()]))
Santa Barbara 93103
Charlottesville 22903

Exercise 3.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.

In [134]:
city_zip = {
    'Santa Barbara':93103, 
    'Charlottesville':22903
}

# for cit in city_zip.keys():
for cit in city_zip:
    print(cit, city_zip[cit])
Santa Barbara 93103
Charlottesville 22903

Exercise 3.8¶

Write a list comprehension that takes a list of numeric values \ and returns a list of their cubes.

In [57]:
vals = [1, 2, 3, 4]
cubes = [val**3 for val in vals]
cubes 
Out[57]:
[1, 8, 27, 64]

Exercise 3.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.

In [80]:
strs = ['99', 'red balloons', 'floating', 'in the', 'summer sky.', '16', 'candles']
num_list = [st for st in strs if st.isdigit()]
num_list
Out[80]:
['99', '16']

Without the function ...

In [78]:
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 3.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]
}
In [135]:
grid = {
    'max_depth': [5,10], 
    'ntrees': [100,200,300],
    'regularization': [11, 12],
    'max_iter': [10,20]
}
In [112]:
grid_max = {key:grid[key] for key in grid.keys() if 'max' in key}
In [113]:
grid_max
Out[113]:
{'max_depth': [5, 10], 'max_iter': [10, 20]}

Now create a dictionary with the same keys but only the maximum values of each associated list.

In [114]:
new_grid = {}
for key in grid:
    new_grid[key] = max(grid[key]) 
In [115]:
new_grid
Out[115]:
{'max_depth': 10, 'ntrees': 300, 'regularization': 12, 'max_iter': 20}
In [116]:
new_grid = {key:max(grid[key]) for key in grid}
In [117]:
new_grid
Out[117]:
{'max_depth': 10, 'ntrees': 300, 'regularization': 12, 'max_iter': 20}

Exercise 3.11¶

Given the dict letter_to_idx which maps some letters to index values,
use a dict comprehension to create a reversed dict, idx_to_letter mapping the index values to the letters.

letter_to_idx = {
    'a': 0, 
    'b': 1, 
    'c': 2
}
In [118]:
letter_to_idx = {
    'a': 0, 
    'b': 1, 
    'c': 2
}
In [119]:
idx_to_letter = {letter_to_idx[k]:k for k in letter_to_idx.keys()}  
In [120]:
idx_to_letter
Out[120]:
{0: 'a', 1: 'b', 2: 'c'}

Or try this:

In [121]:
idx_to_letter2 = {v:k for k, v in letter_to_idx.items()}
In [122]:
idx_to_letter2
Out[122]:
{0: 'a', 1: 'b', 2: 'c'}
In [ ]: