You are almost done with the course. Nice job.
Fortunately, we have a couple more interesting problems for you before you go.
As always, run the setup code below before working on the questions.
from learntools.core import binder; binder.bind(globals())
from learntools.python.ex6 import *
print('Setup complete.')
Setup complete.
Let's start with a string lightning round to warm up. What are the lengths of the strings below?
For each of the five strings below, predict what len()
would return when passed that string. Use the variable length
to record your answer, then run the cell to check whether you were right.
a = ""
length = 0
q0.a.check()
Correct:
The empty string has length zero. Note that the empty string is also the only string that Python considers as False when converting to boolean.
b = "it's ok"
length = 7
q0.b.check()
Correct:
Keep in mind Python includes spaces (and punctuation) when counting string length.
c = 'it\'s ok'
length = 7
q0.c.check()
Correct:
Even though we use different syntax to create it, the string c
is identical to b
. In particular, note that the backslash is not part of the string, so it doesn't contribute to its length.
d = """hey"""
length = 3
q0.d.check()
Correct:
The fact that this string was created using triple-quote syntax doesn't make any difference in terms of its content or length. This string is exactly the same as 'hey'
.
e = '\n'
length = 1
q0.e.check()
Correct:
The newline character is just a single character! (Even though we represent it to Python using a combination of two characters.)
There is a saying that "Data scientists spend 80% of their time cleaning data, and 20% of their time complaining about cleaning data." Let's see if you can write a function to help clean US zip code data. Given a string, it should return whether or not that string represents a valid zip code. For our purposes, a valid zip code is any string consisting of exactly 5 digits.
HINT: str
has a method that will be useful here. Use help(str)
to review a list of string methods.
def is_valid_zip(zip_code):
"""Returns whether the input string is a valid (5 digit) zip code
"""
return len(zip_code) == 5 and zip_code.isnumeric()
# Check your answer
q1.check()
Correct
#q1.hint()
#q1.solution()
A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles.
Your function should meet the following criteria:
def word_search(doc_list, keyword):
"""
Takes a list of documents (each document is a string) and a keyword.
Returns list of the index values into the original list for all documents
containing the keyword.
Example:
doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
>>> word_search(doc_list, 'casino')
>>> [0]
"""
indexes=[]
for i, doc in enumerate(doc_list):
normalize_tokens = [word.strip('.,').lower() for word in doc.split()]
if keyword.lower() in normalize_tokens :
indexes.append(i)
return indexes
# Check your answer
q2.check()
Correct
q2.hint()
q2.solution()
Hint: Some methods that may be useful here: str.split()
, str.strip()
, str.lower()
.
Solution:
def word_search(documents, keyword):
# list to hold the indices of matching documents
indices = []
# Iterate through the indices (i) and elements (doc) of documents
for i, doc in enumerate(documents):
# Split the string doc into a list of words (according to whitespace)
tokens = doc.split()
# Make a transformed list where we 'normalize' each word to facilitate matching.
# Periods and commas are removed from the end of each word, and it's set to all lowercase.
normalized = [token.rstrip('.,').lower() for token in tokens]
# Is there a match? If so, update the list of matching indices.
if keyword.lower() in normalized:
indices.append(i)
return indices
Now the researcher wants to supply multiple keywords to search for. Complete the function below to help her.
(You're encouraged to use the word_search
function you just wrote when implementing this function. Reusing code in this way makes your programs more robust and readable - and it saves typing!)
def multi_word_search(doc_list, keywords):
"""
Takes list of documents (each document is a string) and a list of keywords.
Returns a dictionary where each key is a keyword, and the value is a list of indices
(from doc_list) of the documents containing that keyword
>>> doc_list = ["The Learn Python Challenge Casino.", "They bought a car and a casino", "Casinoville"]
>>> keywords = ['casino', 'they']
>>> multi_word_search(doc_list, keywords)
{'casino': [0, 1], 'they': [1]}
"""
dictionary={word:[] for word in keywords}
for i, doc in enumerate(doc_list):
normalize_tokens = [word.strip('.,').lower() for word in doc.split()]
for keyword in keywords:
if keyword.lower() in normalize_tokens :
dictionary[keyword].append(i)
return dictionary
# Check your answer
q3.check()
Correct
q3.solution()
You've learned a lot. But even the best programmers rely heavily on "libraries" of code from other programmers. You'll learn about that in the last lesson.
Have questions or comments? Visit the Learn Discussion forum to chat with other Learners.