Sets and Dictionaries Answers¶
Dictionary Exercises¶
Translate¶
Make a program translate.py, that will take a list of words in one language and transliterate each word into another language.
Here is an (over-simplified) example translation dictionary for translating from Spanish to English:
>>> words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'}
An example of how this program should work:
$ python translate.py el gato esta en la casa
the cat is in the house
Answers
import sys
words = sys.argv[1:]
translation = []
for w in words:
translation.append(words[w])
print(" ".join(translation))
Count Words¶
- Create a string containing the
Declaration of Independence - Create a dictionary recording the number of times all two letter words occur in the Declaration of Independence. The keys should be words and the values should be the count.
As a bonus exercise, remove words that are not alphanumeric.
Answers
With if statement:
count = {}
for word in declaration.split():
if len(word) == 2 and word.isalpha():
if word not in count:
count[word] = 0
count[word] += 1
With if-else statement:
count = {}
for word in declaration.split():
if len(word) == 2 and word.isalpha():
if word in count:
count[word] += 1
else:
count[word] = 1
With dict.setdefault:
count = {}
for word in declaration.split():
if len(word) == 2 and word.isalpha():
count.setdefault(word, 0)
count[word] += 1
With dict.get default:
count = {}
for word in declaration.split():
if len(word) == 2 and word.isalpha():
count[word] = count.get(word, 0) + 1
Anagrams¶
Make a program anagrams.py that takes two words and prints out whether or not the two words are anagrams.
$ python anagrams.py tea eat
anagrams :)
$ python anagrams.py tea treat
not anagrams :(
$ python anagrams.py sink skin
anagrams :)
$ python anagrams.py sinks skin
not anagrams :(
Encode¶
Make a program encode.py that takes a word and prints out the numeric representation of each letter in the word, starting with A at 1.
Example usage:
$ encode.py z
26
$ encode.py abc
1 2 3
$ encode.py Trey
20 18 5 25
Decode¶
Make a program decode.py that takes any number of integers as arguments and prints the word that the integers represent (1 is the letter A, 2 is B, 3 is C, etc.).
Example usage:
$ encode.py 26
Z
$ encode.py 1 2 3
ABC
$ encode.py 20 18 5 25
TREY
Set Exercises¶
Where to Eat¶
Three of us want to eat lunch together but we can’t decide where to eat. Lets make three sets containing all of the restaurants we want to eat at and take the intersection of these sets to determine where to eat.
>>> restaurants_trey = {'Habaneros', 'Karl Strauss', 'Opera', 'Punjabi Tandoor'}
>>> restaurants_diane = {'Siam Nara', 'Punjabi Tandoor', 'Opera'}
>>> restaurants_peter = {'Karl Strauss', 'Opera', 'Habaneros'}
Answers
Methods:
>>> restaurants_trey.intersection(restaurants_diane).intersection(restaurants_peter)
{'Opera'}
Operators:
>>> restaurants_trey & restaurants_diane & restaurants_peter
{'Opera'}
set.intersection class method:
>>> set.intersection(restaurants_trey, restaurants_diane, restaurants_peter)
{'Opera'}
Count favorites¶
Use the three restaurant sets we used before to create a dictionary containing the number of times each restaurant occurs in a set:
>>> restaurants_trey = {'Habaneros', 'Karl Strauss', 'Opera', 'Punjabi Tandoor'}
>>> restaurants_diane = {'Siam Nara', 'Punjabi Tandoor', 'Opera'}
>>> restaurants_peter = {'Karl Strauss', 'Opera', 'Habaneros'}
So one of the entries in the dictionary would be 'Opera' : 3.
Answers
def count_favs(groups):
favs = {}
for group in groups:
for item in group:
favs.setdefault(item, 0)
favs[item] += 1
return favs
Bonus: Most common¶
Create a function that accepts a list 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}
>>> most_common([restaurants_trey, restaurants_diane, restaurants_peter])
{'Opera'}
Answers
def count_favs(groups):
favs = {}
for group in groups:
for item in group:
favs.setdefault(item, 0)
favs[item] += 1
return favs
def most_common(groups):
item_counts = count_favs(groups)
num = max(item_counts.values())
most = set()
for item, count in item_counts.items():
if count == num:
most.add(item)
return most
Bonus: Check For Duplicates¶
Write a function is_unique that takes a list as input and returns True if the list contains no duplicate elements.
Try running is_unique on the following lists:
>>> numbers1 = [1, 2, 4, 2]
>>> numbers2 = [1, 2, 3, 4]
Answers
def is_unique(items):
return len(items) == len(set(items))
Zip Exercises¶
Parse two-line CSV data¶
Make a function parse_row that accepts a string consisting of two lines of comma-separated data and parses it, returning a dictionary where the keys are elements from the first row and the values are from the second row.
Example usage:
>>> color_data = "purple,indigo,red,blue,green\n0.15,0.25,0.3,0.05,0.25"
>>> parse_row(color_data)
{'blue': '0.05', 'green': '0.25', 'purple': '0.15', 'red': '0.3', 'indigo': '0.25'}
Answers
Without unpacking:
def parse_row(input_data):
rows = input_data.split("\n")
row1 = rows[0].split(",")
row2 = rows[1].split(",")
new_dict = dict(zip(row1, row2))
return new_dict
With unpacking (more idiomatic):
def parse_row(input_data):
color_row, ratio_row = input_data.split("\n")
colors = color_row.split(",")
ratios = ratio_row.split(",")
return dict(zip(colors, ratios))
Double-valued Dictionary¶
Make a function dict_from_truple that accepts a list of three-item tuples and returns a dictionary where the keys are the first item of each tuple and the values are a two-tuple of the remaining two items of each input tuple.
Example usage:
>>> dict_from_truple([(1, 2, 3), (4, 5, 6), (7, 8, 9)])
{1: (2, 3), 4: (5, 6), 7: (8, 9)}
Answers
Without unpacking:
def dict_from_truple(input_list):
new_dict = {}
for tup in input_list:
new_dict[tup[0]] = (tup[1], tup[2])
return new_dict
With unpacking (more idiomatic):
def dict_from_truple(input_list):
truple_dict = {}
for key, value1, value2 in input_list:
truple_dict[key] = (value1, value2)
return truple_dict
Bonus: Multi-valued Dictionary¶
Rewrite dict_from_truple to accept a list of tuples of any length and return a dictionary which uses the first item of each tuple as keys and all subsequent items as values.
Example usage:
>>> dict_from_truple([(1, 2, 3, 4), (5, 6, 7, 8)])
{1: (2, 3, 4), 5: (6, 7, 8)}
>>> dict_from_truple([(1, 2, 3), (4, 5, 6), (7, 8, 9)])
{1: (2, 3), 4: (5, 6), 7: (8, 9)}
Answers
Without tuple unpacking:
def dict_from_truple(input_list):
new_dict = {}
for tup in input_list:
new_dict[tup[0]] = (tup[1:])
return new_dict
With unpacking (more idiomatic):
def dict_from_truple(input_list):
truple_dict = {}
for key, *values in input_list:
truple_dict[key] = tuple(values)
return truple_dict
Argument Unpacking Exercises¶
Product¶
Write a product function that takes any number of arguments and multiplies them together, returning the result. Example:
>>> product(10)
10
>>> product(5, 6, 8)
240
Answers
def product(*args):
result = 1
for arg in args:
result *= arg
return result
Unzip¶
Create a function unzip that does the opposite of zip.
Example:
>>> unzip([(0, 1), (2, 3)])
[(0, 2), (1, 3)]
Answers
def unzip(items):
return list(zip(*items))
HTML Tag¶
Make a function that accepts a positional argument and keyword arguments and generates an HTML tag using them.
Example:
>>> html_tag("input", type="email", name="email", placeholder="E-mail address")
'<input placeholder="E-mail address" name="email" type="email">'
>>> img_tag = html_tag("img", src="https://placehold.it/10x10", alt="Placeholder")
>>> img_tag
'<img src="https://placehold.it/10x10" alt="Placeholder">'
Answers
Manual string building:
def html_tag(cmd, **kwargs):
tag = '<' + cmd
for param, value in kwargs.items():
tag += ' ' + param + '="' + value + '"'
tag += '>'
return tag
Building string with format and join (more idiomatic):
def html_tag(tag_name, **attributes):
attr_list = []
for param, value in attributes.items():
attr_list.append('{}="{}"'.format(param, value))
return "<{tag} {attrs}>".format(tag=tag_name, attrs=" ".join(attr_list))