Comprehensions Answers¶
Comprehension Exercises¶
Tip
You should use at least one list comprehension in each of these exercises!
Starting with a vowel¶
Make a function that accepts a list of names and returns a new list containing all names that start with a vowel. It should work like this:
>>> names = ["Alice", "Bob", "Christy", "Jules"]
>>> vowel_names(names)
['Alice']
>>> names = ["Scott", "Arthur", "Jan", "Elizabeth"]
>>> vowel_names(names)
['Arthur', 'Elizabeth']
Answers
def vowel_names(names):
return [n for n in names if n[0].upper() in "AEIOU"]
Power List By Index¶
Make a function, power_list, that accepts a list of numbers and returns a new list that contains each number raised to the i-th power where i is the index of that number in the given list. For example:
>>> power_list([3, 2, 5])
[1, 2, 25]
>>> numbers = [78, 700, 82, 16, 2, 3, 9.5]
>>> power_list(numbers)
[1, 700, 6724, 4096, 16, 243, 735091.890625]
Answers
def power_list(numbers):
return [n ** i for i, n in enumerate(numbers)]
Divisible¶
Make a list of all numbers between 100 and 300 that are divisible by both 6 and 10.
Answers
[n for n in range(100, 301) if n % 6 == 0 and n % 10 == 0]
With step:
[n for n in range(100, 301, 10) if n % 6 == 0]
Flatten a Matrix¶
Create a function flatten, that will take a matrix (a list of lists) and return a flattened version of the matrix.
>>> matrix = [[row * 3 + incr for incr in range(1, 4)] for row in range(4)]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> flatten(matrix)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Answers
def flatten(matrix):
return [item for row in matrix for item in row]
Secret Message¶
- Create a string containing the
declaration of independence - Get a list of all uppercase letters in the declaration of independence
- Find a secret 4 letter word in this uppercase letter list. The word starts at index 374 ends at index 382, and skips every other letter
Answers
capitals = [c for c in declaration if c.isupper()]
word = "".join(capitals[374:382:2])
More Comprehension Exercises¶
ASCII Strings¶
Create a function that accepts a list of strings and returns a dictionary containing the strings as keys and a list of corresponding ASCII character codes as values.
>>> words = ["hello", "bye", "yes", "no", "python"]
>>> get_ascii_codes(words)
{'yes': [121, 101, 115], 'hello': [104, 101, 108, 108, 111], 'python': [112, 121, 116, 104, 111, 110], 'no': [110, 111], 'bye': [98, 121, 101]}
Answers
def get_ascii_codes(words):
return {word: [ord(c) for c in word] for word in words}
Factors¶
Create a function which takes a set of numbers and makes a dictionary containing the numbers as keys and all factors as values.
>>> get_all_factors({1, 2, 3, 4})
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4]}
>>> get_all_factors({62, 293, 314})
{314: [1, 2, 157, 314], 293: [1, 293], 62: [1, 2, 31, 62]}
Hint
You can use this function to find the factors of any number:
def get_factors(number):
return [n for n in range(1, number + 1) if number % n == 0]
Answers
def get_factors(number):
return [n for n in range(1, number + 1) if number % n == 0]
def get_all_factors(numbers):
return {n: get_factors(n) for n in numbers}
Flipped Dictionary¶
Make a function flip_dict, that flips dictionary keys and values.
Example usage:
>>> flip_dict({'Python': "2015-09-15", 'Java': "2015-09-14", 'C': "2015-09-13"})
{'2015-09-13': 'C', '2015-09-15': 'Python', '2015-09-14': 'Java'}
Answers
def flip_dict(dictionary):
return {v: k for k, v in dictionary.items()}
Most common¶
Create a function that accepts any number of sets and returns a set of the most common items from each of the given sets.
For example:
>>> most_common({1, 2}, {2, 3}, {3, 4})
{2, 3}
>>> restaurants_trey = {'Habaneros', 'Karl Strauss', 'Opera', 'Punjabi Tandoor'}
>>> restaurants_diane = {'Siam Nara', 'Punjabi Tandoor', 'Opera'}
>>> restaurants_peter = {'Karl Strauss', 'Opera', 'Habaneros'}
>>> most_common(restaurants_trey, restaurants_diane, restaurants_peter)
{'Opera'}
Answers
With a for loop
def most_common(*sets):
occurrences = {}
for s in sets:
for item in s:
occurrences.setdefault(item, 0)
occurrences[item] += 1
most = max(occurrences.values())
return {i for i, count in occurrences.items() if count == most}
With a set and list.count
def most_common(*sets):
items = [x for s in sets for x in s]
unique_items = set(items)
occurrences = {x: items.count(x) for x in unique_items}
most = max(occurrences.values())
return {i for i, count in occurrences.items() if count == most}
X marks the spot¶
- Create a string containing the
Declaration of Independence - Find all words in the Declaration of Independence that contain the letter “x”
Answers
x_words = {word for word in declaration.split() if "x" in word.lower()}
All Together¶
Write a function all_together that takes any number of iterables and strings them together. Try using a generator expression to do it.
Example:
>>> list(all_together([1, 2], (3, 4), "hello"))
[1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o']
>>> nums = all_together([1, 2], (3, 4))
>>> list(all_together(nums, nums))
[1, 2, 3, 4]
Perfect Cube¶
A perfect cube is a number which has a cube-root which is an integer.
You can use this function to determine whether a number is a perfect cube:
def is_perfect_cube(n):
return round(n ** (1/3)) ** 3 == n
Find the first perfect cube over 100,000,000.
Head¶
Make a head that gives the first n items of a given iterable.
>>> list(head([1, 2, 3, 4, 5], n=2))
[1, 2]
>>> first_4 = head([1, 2, 3, 4, 5], n=4)
>>> zip(first_4, first_4)
[(1, 2), (3, 4)]
Answers
def head(iterable, n):
return (
item
for item, _ in zip(iterable, range(n))
)