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?
val = 5
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')
else:
print('bucket 4')
bucket 4
Write code that does the following:
xx = [-2, 8, 0, 5, 6]
max_val
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
for x in xx:
print(x) if x < max_val else print('max_val')
-2 max_val 0 5 6
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
Write code that does the following:
it
to $0$max_iter
to $100$it
< max_iter
, does the following:it
equals $0$ or it
is divisible by $10$, print it
. Hint: use modulo operator %
it
by $1$it
>= max_iter
, the program should quitit = 0
max_iter = 100
while it < max_iter:
if (it == 0) or (it % 10 == 0):
print(it)
it += 1
Create a list of four strings that are capitalized proper nouns.
Write a for
loop to iterate over the strings and:
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
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
beatles = iter(names)
for name in iter(beatles):
print(name)
John Paul George Ringo
beatles = iter(names)
_ = [print(next(beatles)) for i in range(len(names))]
John Paul George Ringo
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 cit, zi in city_zip.items():
print(cit, zi)
Santa Barbara 93103 Charlottesville 22903
_ = [print(cit, zi) for cit, zi in city_zip.items()]
Santa Barbara 93103 Charlottesville 22903
print("\n".join([f"{cit} {zi}" for cit, zi in city_zip.items()]))
Santa Barbara 93103 Charlottesville 22903
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 cit in city_zip:
print(cit, city_zip[cit])
Santa Barbara 93103 Charlottesville 22903
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]
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']
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 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}
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
}
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'}