course 1: CRASH COURSE ON PYTHON

Module 4: Strings, Lists and Dictionaries

GOOGLE IT AUTOMATION WITH PYTHON PROFESSIONAL CERTIFICATE

Complete Coursera Study Guide

Last updated:

INTRODUCTION – Strings, Lists and Dictionaries

In this module you’ll dive into more advanced ways to manipulate strings using indexing, slicing, and advanced formatting. You’ll also explore the more advanced data types: lists, tuples, and dictionaries. You’ll learn to store, reference, and manipulate data in these structures, as well as combine them to store complex data structures.

Learning Objectives

  • Manipulate strings using indexing, slicing, and formatting
  • Use lists and tuples to store, reference, and manipulate data
  • Leverage dictionaries to store more complex data, reference data by keys, and manipulate data stored
  • Combine the String, List, and Dictionary data types to construct complex data structures

PRACTICE QUIZ: STRINGS

1. Fill in the blanks to complete the is_palindrome function. This function checks if a given string is a palindrome. A palindrome is a string that contains the same letters in the same order, whether the word is read from left to right or right to left. Examples of palindromes are words like kayak and radar, and phrases like “Never Odd or Even”. The function should ignore blank spaces and capitalization when checking if the given string is a palindrome. Complete this function to return True if the passed string is a palindrome, False if not.

kpIyIHV1aT3BrSUu4c7YmL wUXYTBO1tcG nNSybhm9vwfGlv6xK3u dcHuSVHDJli16gBLBq0c16ZFZKcwZ 4vUlgW66xKVDpbxRLtD84tj5gG8oUwPz6gMqkMIRz8ab3SfY

  • Answer:
def is_palindrome(input_string):
    # Two variables are initialized as string date types using empty 
    # quotes: "reverse_string" to hold the "input_string" in reverse
    # order and "new_string" to hold the "input_string" minus the 
    # spaces between words, if any are found.
    new_string = ""
    reverse_string = ""


    # Complete the for loop to iterate through each letter of the
    # "input_string"
    for letter in input_string:


        # The if-statement checks if the "letter" is not a space.
        if letter != " ":


            # If True, add the "letter" to the end of "new_string" and
            # to the front of "reverse_string". If False (if a space
            # is detected), no action is needed. Exit the if-block.
            new_string = new_string + letter
            reverse_string = letter + reverse_string


    # Complete the if-statement to compare the "new_string" to the
    # "reverse_string". Remember that Python is case-sensitive when
    # creating the string comparison code. 
    if new_string.lower()==reverse_string.lower():


        # If True, the "input_string" contains a palindrome.
        return True
        
    # Otherwise, return False.
    return False


print(is_palindrome("Never Odd orEven")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True

Woohoo! You’re quickly becoming the Python string expert!

2. Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase “X miles equals Y km”, with Y having only 1 decimal place. For example, convert_distance(12) should return “12 miles equals 19.2 km”.

ll7St8qxTAr2XcFP cttbsBaXqwvgOlQR5H14tWA1r44ncZ1UsnmIQYmz udeg9tq3TEEeb4N5ny38IH8y35QYPIo9 BTPfmbYp7HFrvyKj9AIp932VnsmMwvn1ZZlU0kyH49pxKaU0mYl I0YHUIg

  • Answer:
def convert_distance(miles):
    km = miles * 1.6 
    result = "{} miles equals {:.1f} km".format(miles,(km))
    return result


print(convert_distance(12)) # Should be: 12 miles equals 19.2 km
print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km
print(convert_distance(11)) # Should be: 11 miles equals 17.6 km

Congrats! You’re getting the hang of formatting strings hooray!

3. If we have a string variable named Weather = “Rainfall”, which of the following will print the substring “Rain” or all characters before the “f”?

  • print(Weather[:4]) (CORRECT)
  • print(Weather[4:])
  • print(Weather[1:4])
  • print(Weather[:”f”])

Correct. Formatted this way, the substring preceding the character “f”, which is indexed by 4, will be printed.

4. Fill in the gaps in the nametag function so that it uses the format method to return first_name and the first initial of last_name followed by a period. For example, nametag(“Jane”, “Smith”) should return “Jane S.”

mWJujFxinA67yB10hzDhVap TQaL2Ujavnp f61ykw2Ay YN cGIBKRgiPshDdbyRK1MoRGtv09L0EaCi8xEymsiib DLxNzU J0vWSHdU7ssWG6Up7U5xCPUISA4NDe4eF5FlMd kYp5DircZd2vw

  • Answer:
def nametag(first_name, last_name):
            return("{} {}.".format(first_name, last_name[0]))


print(nametag("Jane", "Smith")) 
# Should display "Jane S." 
print(nametag("Francesco", "Rinaldi")) 
# Should display "Francesco R." 
print(nametag("Jean-Luc", "Grand-Pierre")) 
# Should display "Jean-Luc G."

Great work! You remembered the formatting expression to limit how many characters in a string are displayed.

5. The replace_ending function replaces a specified substring at the end of a given sentence with a new substring. If the specified substring does not appear at the end of the given sentence, no action is performed and the original sentence is returned. If there is more than one occurrence of the specified substring in the sentence, only the substring at the end of the sentence is replaced. For example, replace_ending(“abcabc”, “abc”, “xyz”) should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending(“abcabc”, “ABC”, “xyz”) should return abcabc (no changes made).

oxZ8cApjgMzi1nsBOj165VOHJEwQuUZdkUlx1 o9tjl3LcUlovICBOQiSPU3mXOGd9B8FcY wzf3nsGFXRxbUyeBnr1A0YcxOPe1EyVJZRSY BvByKr 2xSCHn 2uRl6cZ5Z3G9LmRCF7M2ZusKa3Q

  • Answer:
def replace_ending(sentence, old, new):
    # Check if the old substring is at the end of the sentence 
    if sentence[-len(old):] == old:
        # Using i as the slicing index, combine the part
        # of the sentence up to the matched string at the 
        # end with the new string
        i = len(sentence) - len(old)
        new_sentence = sentence[:i] + new
        return new_sentence


    # Return the original sentence if there is no match 
    return sentence
    
# Test cases
print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) 
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april")) 
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April")) 
# Should display "The weather is nice in April"

Outstanding! Look at all of the things that you can do with these string commands!

6. Try using the index method yourself now!
Using the index method, find out the position of “x” in “supercalifragilisticexpialidocious”.

vY0Gi0 4trXz w1 Hiiqr YtpIyUyU4g3MvxL iT5gvrI7kDbwWCja9PdlO7Fs 9uOZSYaWnrfmGV393baLdwVQF9zzlawi9ZHuiUcK

  • Answer:
word = "supercalifragilisticexpialidocious"
print(word.index('x'))

Right on! The index method is a very useful way of working with strings, and not having to do the hard work manually.

7. Modify the student_grade function using the format method, so that it returns the phrase “X received Y% on the exam”. For example, student_grade(“Reed”, 80) should return “Reed received 80% on the exam”.

  • Answer:
def student_grade(name, grade):
    return "{} received {}% on the exam".format(name,grade)


print(student_grade("Reed", 80))
print(student_grade("Paige", 92))
print(student_grade("Jesse", 85)

You got it! Your string formatting skills are coming along nicely!

PRACTICE QUIZ: LISTS

1. Fill in the blank using a for loop. With the given list of “filenames”, this code should rename all files with the extension .hpp to the extension .h. The code  should then generate a new list called “new_filenames” that contains the file names with the new extension.
You are given a list of filenames like this:
filenames = [“program.c”, “stdio.hpp”, “sample.hpp”, “a.out”, “math.hpp”, “hpp.out”]
Output the list with all of the “.hpp” files renamed to “.h”. Leave the other filenames alone. For this question, you must use a for loop to create the list.

BDcuxrLCgyq6DzzREG7YDr1Jc caNr5c4z qrGB8XWJb4zWHhKJsyz8juNKZVdn87 Ye6QaiY3EhaJAMItZLywpALSYGpyP9uIYNTUP

  • Answer:
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]


new_filenames = []
for filename in filenames:
    if filename.endswith("hpp"):
        new_filenames.append(filename[:-3] + "h")
    else:
        new_filenames.append(filename)


print(new_filenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

Great work! You’re starting to see the benefits of knowing how to operate with lists and strings.

2. Fill in the blank using a list comprehension. With the given list of “filenames”, this code should rename all files with the extension .hpp to the extension .h. The code function should then generate a new list called “new_filenames” that contains the filenames with the new extension
You are given a list of filenames like this:
filenames = [“program.c”, “stdio.hpp”, “sample.hpp”, “a.out”, “math.hpp”, “hpp.out”]
Output the list with all of the “.hpp” files renamed to “.h”. Leave the other filenames alone. For this question, you must use list comprehension to create the list.

X Fq7BiA 0T2WAufU vwJebnOJsQgHp0KAcf4AU7w3o4GvcD5Kn6VastRFr J0LxJPnzDMTt8OpS4IleMEj9GZvfxz

  • Answer:
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]


new_filenames = []
for filename in filenames:
    if filename.endswith("hpp"):
        new_filenames.append(filename[:-3] + "h")
    else:
        new_filenames.append(filename)


print(new_filenames)
# Should print ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

Great work! You’re starting to see the benefits of knowing how to operate with lists and strings.

3. Create a function that turns text into pig latin. Pig latin is a simple text transformation that modifies each word by:

  • moving the first character to the end of each word;
  • then appending the letters “ay” to the end of each word.

For example, python ends up as ythonpay.

PcsFHVNaUmZ7A3HsrCVtUq3TTW2s9tiLXENMrBBB9I9VQ6kDL5QEfH3uzgzoZndhnZdF1ZmQ1E3jkuJlzbQ7 OK sYNa6pSVq1rfFJKJYm6yq8bLJvq7NIHS0jTbNbTe4WybnMhSyT46szVeVzP1XQ

  • Answer:
def pig_latin(text):
    say = ""
    # Separate the text into words
    words = text.split()
    for word in words:
        # Create the pig latin word and add it to the list
        pig_word = word[1:] + word[0] + "ay"
        say += pig_word + " "
    # Turn the list back into a phrase
    return say.strip()


# Example usage:
print(pig_latin("hello how are you"))  # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun"))  # Should be "rogrammingpay niay ythonpay siay unfay"

Nice! You’re using some of the best string and list functions to make this work. Great job!

4. Which list method can be used to add a new element to a list at a specified index position?

  • list.pop(index)
  • list.insert(index, x) (CORRECT)
  • list.add(index, x)
  • list.append(x)

Correct! The list.insert(index, x) method will insert the given “x” element into the list at the specified index position.

5. Tuples and lists are very similar types of sequences. What is the main thing that makes a tuple different from a list?

  • A tuple is mutable
  • A tuple contains only numeric characters
  • A tuple is immutable (CORRECT)
  • A tuple can contain only one type of data at a time

Awesome! Unlike lists, tuples are immutable, meaning they can’t be changed.

6. Fill in the blanks to complete the “biograpy_list” function. The “biograpy_list” function reads in a list of tuples “people”, which contains the name, age, and profession of each “person”. Then, prints the sentence “__ is _ years old and works as __.”. For example, “biograpy_list((‘Ken’, 30, “a Chef”)” should print: “Ken is 30 years old and works as a Chef.”

qHvpH6YG9YrAFX7pOWRYnHelQ4MLVWmQnO8JJ56GCuidmhjiwggO00G1LTu4c1HVdoHZde5aS

  • Answer:
def biography_list(people):
    # Iterate over each "person" in the given "people" list of tuples.
    for person in people:
        # Separate the 3 items in each tuple into 3 variables:
        # "name", "age", and "profession"
        name, age, profession = person


        # Format the required sentence and place the 3 variables
        # in the correct placeholders using the .format() method.
        print("{} is {} years old and works as {}".format(name, age, profession))


# Call to the function:
biography_list([('Ira', 30, "a Chef"), ("Raj", 35, 'a Lawyer'), ('Maria', 25, "an Engineer")])

Well done! See how the format methodology combines with tuple functionality to easily create interesting code!

7. Using the “split” string method from the preceding lesson, complete the get_word function to return the {n}th word from a passed sentence. For this example, run the print statements one at a time.  Delete the other 3 print statements to do this. For example, get_word(“This is a lesson about lists”, 4) should return “lesson”, which is the 4th word in this sentence. Hint: remember that list indexes start at 0, not 1.

AwdrPM6vkLipCRB1DjqkW0dwmf2OdV272ixqJC9fNYke4Tw976Rqp3quXrbP8AR kVYk0 VXbQhikpT15uC8VOPpFmak8HtDFSJBJ7ZvU gmz9BcdCt9ggLH1mz gXhU5pResDHzvWwjOYcW2BkmKQ

  • Answer:
def get_word(sentence, n):
    # Only proceed if n is positive 
    if n > 0:
        words = sentence.split()
        # Only proceed if n is not more than the number of words 
        if n <= len(words):
            return(words[n-1])
    return("")


print(get_word("This is a lesson about lists", 4)) # Should print: lesson
print(get_word("This is a lesson about lists", -4)) # Nothing
print(get_word("Now we are cooking!", 1)) # Should print: Now
print(get_word("Now we are cooking!", 5)) # Nothing

Excellent! You’re getting comfortable with string conversions into lists. Now we are really cooking!

8. Let’s use tuples to store information about a file: its name, its type and its size in bytes. Fill in the gaps in this code to return the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places.

RL4FrQBdn dgrKIOw6k BdjaYEKXH3dGQamCRwIHrcQ8m1 azcjaKT0pGYIc2EvIMQsfpJR0650tzZ vG7e27Sd2aJBnpSH8MQ0mY6docjXDGzsFYntlcfJeGg7Zcd917Vwq9QEQombFNVv 3WudmQ

  • Answer:
def file_size(file_info):
    _, _, size = file_info
    return "{:.2f}".format(size / 1024)


print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46
print(file_size(('Notes', 'txt', 496))) # Should print 0.48
print(file_size(('Program', 'py', 1239))) # Should print 1.21

Well done! Aren’t tuples handy to keep the information nicely organized for when we need it?

9. Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is in an even position or an odd position.

gdVX QmYu YSBSgzIqtYZuMbgdiaFmnpKCW6QIPecXUbhwjS6Zlcbz QPUFBd 21xEApM6vdEP8IJRlLQZV CGM5IgTHmVuF7VnBdFVVcwiEKW3W9ohK5TeIgoZ68emp4L6tjPtqNjTK9wKi8Z1CMg

  • Answer:
def skip_elements(elements):
    # code goes here
    return [element for index, element in enumerate(elements) if index % 2 == 0]


print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']

Great job! The enumerate function sure makes things easier, doesn’t it?

10. The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1.

SwwNQs mWvqiQbMUv0X6L8lmSVrT4jB MYrJeG5BS876tchiULYu5iH2KB9B HUWClgQiE5MU94du PXmHFclFbNoE0iHiZl iQn2OUr

  • Answer:
def odd_numbers(n):
    return [x for x in range(1, n + 1) if x % 2 != 0]


print(odd_numbers(5))  # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  # Should print [1]
print(odd_numbers(-1)) # Should print []

Excellent! You’re using the power of list comprehension to do a lot of work in just one line!

MODULE 4 GRADED ASSESSMENT

1. The format of the input variable “address_string” is: numeric house number, followed by the street name which may contain numbers and could be several words long (e.g., “123 Main Street”, “1001 1st Ave”, or “55 North Center Drive”).
Complete the string methods needed in this function so that input like “123 Main Street” will produce the output “House number 123 on a street named Main Street”. This function should:

  • accept a string through the parameters of the function;
  • separate the address string into new strings: house_number and street_name; 
  • return the variables in the string format: “House number X on a street named Y”.

  • Answer:
def format_address(address_string):
    house_number = ""
    street_name = ""


    # Separate the house number from the street name.
    address_parts = address_string.split()


    for address_part in address_parts:
        # Complete the if-statement with a string method.
        if address_part.isdigit():
            house_number = address_part
        else:
            street_name += address_part + " "


    # Remove the extra space at the end of the last "street_name".
    street_name = street_name.strip()


    # Use a string method to return the required formatted string.
    formatted_address = f"House number {house_number} on a street named {street_name}"
    return formatted_address


print(format_address("123 Main Street"))
# Should print: "House number 123 on a street named Main Street"


print(format_address("1001 1st Ave"))
# Should print: "House number 1001 on a street named 1st Ave"


print(format_address("55 North Center Drive"))
# Should print "House number 55 on a street named North Center Drive"

Correct

2. Complete the for loop and string method needed in this function so that a function call like “alpha_length(“This has 1 number in it”)” will return the output “17”. This function should:

  • accept a string through the parameters of the function;
  • iterate over the characters in the string;
  • determine if each character is a letter (counting only alphabetic characters; numbers, punctuation, and spaces should be ignored);
  • increment the counter;
  • return the count of letters in the string.

67hgeLWxfQ6xTUJu lCHxpitbAb9Q4HgeND CmjbVC6Yh384YaL G2 uOJDrwEFeJHHwZLhn3ddqeLp9NuarFJbSycdtL7VLn3efz GKTGw56jD14FOHmm4YAMJUimyj04jgfNmTWdv3lRjhA5WNWA

  • Answer:
def alpha_length(string):
    count_alpha = 0
    # Complete the for loop sequence to iterate over "string".
    for char in string:
        # Complete the if-statement using a string method.
        if char.isalpha():
            count_alpha += 1
    return count_alpha


print(alpha_length("This has 1 number in it")) # Should print 17
print(alpha_length("Thisisallletters")) # Should print 16
print(alpha_length("This one has punctuation!")) # Should print 21

Correct

3. Consider the following scenario about using Python lists:
A professor gave his two assistants, Jaime and Drew, the task of keeping an attendance list of students in the order they arrive in the classroom. Drew was the first one to note which students arrived, and then Jaime took over. After the class, they each entered their lists into the computer and emailed them to the professor. The professor wants to combine the two lists into one, in the order of each student’s arrival. Jaime emailed a follow-up, saying that her list is in reverse order. 
Complete the code to combine the two lists into one in the order of: the contents of Drew’s list, followed by Jaime’s list in reverse order, to produce an accurate list of the students as they arrived. This function should:

  • accept two lists through the function’s parameters;
  • reverse the order of “list1”; 
  • combine the two lists so that “list2” comes first, followed by “list1”;
  • return the new list.

  • Answer:
def combine_lists(list1, list2):


  combined_list = [] # Initialize an empty list variable
  list1.reverse() # Reverse the order of "list1"
  list2 += list1 # Combine the two lists 
  combined_list = list2
  return combined_list  
  
Jaimes_list = ["Alma", "Chika", "Benjamin", "Jocelyn", "Oakley"]
Drews_list = ["Minna", "Carol", "Gunnar", "Malena"]


print(combine_lists(Jaimes_list, Drews_list))
# Should print ['Minna', 'Carol', 'Gunnar', 'Malena', 'Oakley', 'Jocelyn', 'Benjamin', 'Chika', 'Alma']

Correct

4. Fill in the blank to complete the “increments” function. This function should use a list comprehension to create a list of numbers incremented by 2 (n+2). The function receives two variables and should return a list of incremented consecutive numbers between “start” and “end” inclusively (meaning the range should include both the “start” and “end” values). Complete the list comprehension in this function so that input like “squares(2, 3)” will produce the output “[4, 5]”.

VACakIiEd5mfN5b3cJtutRvqbFo5jh7Lr9y HCrT XQqSKES0K2ksOejr7YOGNf63N47XIP7FmE43fT1 Owm30Syi03KMk9C9fz5S24DepgH8rhuo

  • Answer:
def increments(start, end):
    return [x + 2 for x in range(start, end + 1)]


print(increments(2, 3))  # Should print [4, 5]
print(increments(1, 5))  # Should print [3, 4, 5, 6, 7]
print(increments(0, 10)) # Should print [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Correct

5. Consider the following scenario about using Python dictionaries:
A teacher is using a dictionary to store student grades. The grades are stored as a point value out of 100. Currently, the teacher has a dictionary setup for Term 1 grades and wants to duplicate it for Term 2. The student name keys in the dictionary should stay the same, but the grade values should be reset to 0.
Complete the “setup_gradebook” function so that input like “{“James”: 93, “Felicity”: 98, “Barakaa”: 80}” will produce a resulting dictionary that contains  “{“James”: 0, “Felicity”: 0, “Barakaa”: 0}”. This function should:

  • accept a dictionary “old_gradebook” variable through the function’s parameters;
  • make a copy of the “old_gradebook” dictionary;
  • iterate over each key and value pair in the new dictionary;
  • replace the value for each key with the number 0;
  • return the new dictionary.

yTus 5E4MnISQJFcgDJ41f7OtUgP3NP3RxRm1iv8OmUvdf5oJ2DT E2moqrRr4LFomLCXXXh22KNVB4IgL4fm0DMujolvxC5xD LpxuXTvLGoZHs SSLcfYaj iYGzPljO UXbZhriL5Z5GMHKwOA

  • Answer:
def setup_gradebook(old_gradebook):
    # Use a dictionary method to create a new copy of the "old_gradebook".
    new_gradebook = old_gradebook.copy()


    # Complete the for loop to iterate over the new gradebook.
    for key in new_gradebook:
        # Use a dictionary operation to reset the grade values to 0.
        new_gradebook[key] = 0


    return new_gradebook


fall_gradebook = {"James": 93, "Felicity": 98, "Barakaa": 80}
print(setup_gradebook(fall_gradebook))
# Should output {'James': 0, 'Felicity': 0, 'Barakaa': 0}

Correct

6. What do the following commands return when genre = “transcendental”?

print(genre[:-8])
print(genre[-7:9])
  • ran, ental
  • endental, tr
  • transc, nd (CORRECT)
  • dental, trans

Correct

7. What does the list “music_genres” contain after these commands are executed?

music_genres = ["rock""pop""country"]

music_genres.append("blues")
  • [‘rock’, ‘pop’, ‘country’, ‘blues’]
  • [‘rock’, ‘pop’, ‘blues’]
  • [‘rock’, ‘blues’, ‘pop’, ‘country’] (CORRECT)
  • [‘rock’, ‘blues’, ‘country’]

8. What do the following commands return?

teacher_names = {"Math": "Aniyah Cook", "Science": "Ines Bisset", "Engineering": "Wayne Branon"}
teacher_names.values()
  • dict_values([‘Aniyah Cook’, ‘Ines Bisset’, ‘Wayne Branon’]) (CORRECT)
  • {“Math”: “Aniyah Cook”,”Science”: “Ines Bisset”, “Engineering”: “Wayne Branon”}
  • [“Math”, “Aniyah Cook”, “Science”, “Ines Bisset”, “Engineering”, “Wayne Branon”]
  • [‘Aniyah Cook’, ‘Ines Bisset’, ‘Wayne Branon”]

Correct

9. Fill in the blank to complete the “highlight_word” function. This function should change the given “word” to its upper-case version in a given “sentence”. Complete the string method needed in this function so that a function call like “highlight_word(“Have a nice day”, “nice”)” will return the output “Have a NICE day”.

3nZ1usBcm8hh7jEVGCtkGgI7ErOQRMTpP7XkMJCw1JJXxe0QfX6pObj9lFNJ7tpbL0BFVrBLqdpIHsCWyW8Z3dhabi2W18zyDPTmjSMt1k2EgY7Lz7

  • Answer:
def highlight_word(sentence, word):
    # Complete the return statement using a string method.
    return sentence.replace(word, word.upper())


print(highlight_word("Have a nice day", "nice"))
# Should print: "Have a NICE day"
print(highlight_word("Shhh, don't be so loud!", "loud"))
# Should print: "Shhh, don't be so LOUD!"
print(highlight_word("Automating with Python is fun", "fun"))
# Should print: "Automating with Python is FUN"

Correct

10. Fill in the blanks to complete the “countries” function. This function accepts a dictionary containing a list of continents (keys) and several countries from each continent (values).  For each continent, format a string to print the names of the countries only. The values for each key should appear on their own line.

  • Answer:
def countries(countries_dict):
    result = ""
    # Complete the for loop to iterate through the key and value items 
    # in the dictionary.
    for continent, countries_list in countries_dict.items():
        # Use a string method to format the required string.
        result += str(countries_list) + "\n"
    return result


print(countries({"Africa": ["Kenya", "Egypt", "Nigeria"], "Asia":["China", "India", "Thailand"], "South America": ["Ecuador", "Bolivia", "Brazil"]}))


# Should print:
# ['Kenya', 'Egypt', 'Nigeria']
# ['China', 'India', 'Thailand']
# ['Ecuador', 'Bolivia', 'Brazil']

Correct

11. Consider the following scenario about using Python dictionaries:
Tessa and Rick are hosting a party. Both sent out invitations to their friends, and each one collected responses into dictionaries, with names of their friends and how many guests each friend was bringing. Each dictionary is a partial guest list, but Rick’s guest list has more current information about the number of guests.
Complete the function to combine both dictionaries into one, with each friend listed only once, and the number of guests from Rick’s dictionary taking precedence, if a name is included in both dictionaries. Then print the resulting dictionary. This function should:

  • accept two dictionaries through the function’s parameters;
  • combine both dictionaries into one, with each key listed only once;
  • the values from the “guests1” dictionary taking precedence, if a key is included in both dictionaries;
  • then print the new dictionary of combined items.

JX76UgbEsE34KegPpp4Y6dL RQNbSFpHzUPdThhZjzlngYsszpMlhias

  • Answer:
def check_guests(guest_list, guest):
  return guest_list[guest] # Return the value for the given key


guest_list = { "Adam":3, "Camila":3, "David":5, "Jamal":3, "Charley":2, "Titus":1, "Raj":6, "Noemi":1, "Sakira":3, "Chidi":5}


print(check_guests(guest_list, "Adam")) # Should print 3
print(check_guests(guest_list, "Sakira")) # Should print 3
print(check_guests(guest_list, "Charley")) # Should print 2

Correct

12. Use a dictionary to count the frequency of numbers in the given “text” string. Only numbers should be counted. Do not count blank spaces, letters, or punctuation. Complete the function so that input like “1001000111101” will return a dictionary that holds the count of each number that occurs in the string  {‘1’: 7, ‘0’: 6}. This function should:

  • accept a string “text” variable through the function’s parameters;
  • initialize an new dictionary;
  • iterate over each text character to check if the character is a number’
  • count the frequency of numbers in the input string, ignoring all other characters;
  • populate the new dictionary with the numbers as keys, ensuring each key is unique, and assign the value for each key with the count of that number;
  • return the new dictionary.

rD5btNpYSYqpo5G3GgxsjnUVgb3hvHx6iNbnOWgOPnUQiMaXHhYFtNq64P10nvi2jzrwYSxXSDzRlRWMlFsw26aBIp9pHHt2HIpZ

  • Answer:
def count_numbers(text):
  # Initialize a new dictionary.
  dictionary = {}
  # Complete the for loop to iterate through each "text" character.
  for char in text:
    # Complete the if-statement using a string method to check if the
    # character is a number.
    if char.isdigit():
      # Complete the if-statement using a logical operator to check if 
      # the number is not already in the dictionary.
      if char not in dictionary:
           # Use a dictionary operation to add the number as a key
           # and set the initial count value to zero.
           dictionary[char] = 0
      # Use a dictionary operation to increment the number count value 
      # for the existing key.
      dictionary[char] += 1
  return dictionary


print(count_numbers("1001000111101"))
# Should be {'1': 7, '0': 6}


print(count_numbers("Math is fun! 2+2=4"))
# Should be {'2': 2, '4': 1}


print(count_numbers("This is a sentence."))
# Should be {}


print(count_numbers("55 North Center Drive"))
# Should be {'5': 2}

Correct

13. What do the following commands return when car_make = “Lamborghini”?

print(car_make[3:-5])
print(car_make[-4:])
print(car_make[:7])
  • mbo, ghin, Lambo
  • bor, hini, Lamborg (CORRECT)
  • borgh, ghin, org
  • mbo, ini, Lamb

Correct

14. Fill in the blanks to complete the “confirm_length” function. This function should return how many characters a string contains as long as it has one or more characters, otherwise it will return 0. Complete the string operations needed in this function so that input like “Monday” will produce the output “6”.

iIiOqAOQYGaUuwpNzNam3Hi1l30zkJoGUF 1qle

  • Answer:
def confirm_length(word):


    # Complete the condition statement using a string operation. 
    if (len(word))>0: 
        # Complete the return statement using a string operation.
        return (len(word))
    else:
        return 0


print(confirm_length("a")) # Should print 1
print(confirm_length("This is a long string")) # Should print 21
print(confirm_length("Monday")) # Should print 6
print(confirm_length("")) # Should print 0

Correct

15. Consider the following scenario about using Python lists:
Employees at a company shared  the distance they drive to work (in miles) through an online survey. These distances were automatically added by Python to a list called “distances” in the order that each employee submitted their distance. Management wants the list to be sorted in the order of the longest distance to the shortest distance.
Complete the function to sort the “distances” list. This function should:

  • sort the given “distances” list, passed through the function’s parameters; ; 
  • reverse the sort order so that it goes from the longest to the shortest distance;
  • return the modified “distances” list.

qFmppVvd4B5LtbS4KOy7cZ25oTcGtmc 8nH mUlg9t w bjWNwO 2jFsojeAQB8rd4I NiQUxZtJZRLKa3OxyJeTbCQqcV7IkpXqgsWGK aEdjlRfL 96LGx7M4PlzfEio 63AZF7FbgGRh u Mw

  • Answer:
def sort_distance(distances):
    distances.sort() # Sort the list
    distances = distances[::-1] # Reverse the order of the list
    return distances


print(sort_distance([2,4,0,15,8,9]))
# Should print [15, 9, 8, 4, 2, 0]

Correct

16. Fill in the blank to complete the “even_numbers” function. This function should use a list comprehension to create a list of even numbers using a conditional if statement with the modulo operator to test for numbers evenly divisible by 2. The function receives two variables and should return the list of even numbers that occur between the “first” and “last” variables exclusively (meaning don’t modify the default behavior of the range to exclude the “end” value in the range). For example, even_numbers(2, 7) should return [2, 4, 6].

rLwo1TBz8W kzWRt4b5jrw 1byuDOH IZ8FXFjb0UAykinUBgY91DIawXqeP FdnBYyzyx1xJWS331yEFr4CckhY4jEz7pShOYLBxYAawJInab5woknXYj6YHSm3sMLX ke7VoR3WlJ4NZPAg JGTg

  • Answer:
def even_numbers(first, last):
  return [i for i in range(first,last) if i%2==0 ]


print(even_numbers(4, 14)) # Should print [4, 6, 8, 10, 12]
print(even_numbers(0, 9))  # Should print [0, 2, 4, 6, 8]
print(even_numbers(2, 7))  # Should print [2, 4, 6]

Correct

17. What does the list “car_makes” contain after these commands are executed?

car_makes = ["Ford", "Volkswagen", "Toyota"]
car_makes.remove("Ford")
  • [null, ‘Porsche’, ‘Toyota’][‘Toyota’, ‘Ford’][”, ‘Porsche’, ‘Vokswagen’, ‘Toyota’]

    [‘Volkswagen’, ‘Toyota’] (CORRECT)

Correct

18. What do the following commands return?

speed_limits = {"street": 35, "highway": 65, "school": 15}
speed_limits["highway"]
  • 65 (CORRECT)
  • {“highway”: 65}
  • [65]
  • [“highway”, 65]

Correct

19. Consider the following scenario about using Python dictionaries and lists:
Tessa and Rick are hosting a party. Before they send out invitations, they want to add all of the people they are inviting to a dictionary so they can also add how many guests each friend is bringing to the party.
Complete the function so that it accepts a list of people, then iterates over the list and adds all of the names (elements) to the dictionary as keys with a starting value of 0. Tessa and Rick plan to update these values with the number of guests their friends will bring with them to the party. Then, print the new dictionary.
This function should:

  • accept a list variable named “guest_list” through the function’s parameter;
  • add the contents of the list as keys to a new, blank dictionary;
  • assign each new key with the value 0;
  • print the new dictionary.

y ckn90wNdhRVoPtK n Xrc27P1z2yWSlUYDzUTNYRDD4

  • Answer:
def setup_guests(guest_list):
    # Initialize a new dictionary
    result = {}
    
    # Iterate over the elements in the list
    for guest in guest_list:
        # Add each list element to the dictionary as a key with 
        # the starting value of 0
        result[guest] = 0
    
    return result


guests = ["Adam","Camila","David","Jamal","Charley","Titus","Raj","Noemi","Sakira","Chidi"]

Correct

20. What does the list “colors” contain after these commands are executed?

colors = ["red", "white", "blue"]
colors.insert(2, "yellow")
  • [‘red’, ‘yellow’, ‘white’, ‘blue’]
  • [‘red’, ‘white’, ‘yellow’, ‘blue’]  (CORRECT)
  • [‘red’, ‘white’, ‘yellow’]
  • [‘red’, ‘yellow’, ‘blue’]

Correct

21. Consider the following scenario about using Python lists:
A professor gave his two assistants, Aniyah and Imani, the task of keeping an attendance list of students in the order they arrived in the classroom. Aniyah was the first one to note which students arrived, and then Imani took over. After class, they each entered their lists into the computer and emailed them to the professor. The professor wants to combine the two lists into one and sort it in alphabetical order.
Complete the code by combining the two lists into one and then sorting the new list. This function should:

  • accept two lists through the function’s parameters;,
  • combine the two lists;
  • sort the combined list in alphabetical order;
  • return the new list.

AjUisz KwVm

  • Answer:
def alphabetize_lists(list1, list2):
    new_list = []  # Initialize a new list.
    new_list.extend(list1)  # Combine the lists.
    new_list.extend(list2)
    new_list.sort()  # Sort the combined lists.
    return new_list


Aniyahs_list = ["Jacomo", "Emma", "Uli", "Nia", "Imani"]
Imanis_list = ["Loik", "Gabriel", "Ahmed", "Soraya"]


print(alphabetize_lists(Aniyahs_list, Imanis_list))
# Should print: ['Ahmed', 'Emma', 'Gabriel', 'Imani', 'Jacomo', 'Loik', 'Nia', 'Soraya', 'Uli']

Correct

22. Complete the function so that input like “This is a sentence.” will return a dictionary that holds the count of each letter that occurs in the string: {‘t’: 2, ‘h’: 1, ‘i’: 2, ‘s’: 3, ‘a’: 1, ‘e’: 3, ‘n’: 2, ‘c’: 1}. This function should:

  • accept a string “text” variable through the function’s parameters;
  • iterate over each character the input string to count the frequency of each letter found, (only letters should be counted, do not count blank spaces, numbers, or punctuation; keep in mind that Python is case sensitive);
  • populate the new dictionary with the letters as keys, ensuring each key is unique, and assign the value for each key with the count of that letter;
  • return the new dictionary.

  • Answer:
def count_letters(text):
    # Initialize a new dictionary.
    dictionary = {}
    # Complete the for loop to iterate through each "text" character and 
    # use a string method to ensure all letters are lowercase.
    for char in text.lower():
        # Complete the if-statement using a string method to check if the
        # character is a letter.
        if char.isalpha():
            # Complete the if-statement using a logical operator to check if 
            # the letter is not already in the dictionary.
            if char not in dictionary:
                # Use a dictionary operation to add the letter as a key
                # and set the initial count value to zero.
                dictionary[char] = 0
            # Use a dictionary operation to increment the letter count value 
            # for the existing key.
            dictionary[char] += 1
    return dictionary


print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}


print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}


print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

Correct

23. What do the following commands return?

host_addresses = {"router": "192.168.1.1", "localhost": "127.0.0.1", "google": "8.8.8.8"}
host_addresses.keys()
  • dict_keys([‘192.168.1.1’, ‘127.0.0.1’, ‘8.8.8.8’])
  • dict_keys([“router”, “192.168.1.1”, “localhost”, “127.0.0.1”, “google”, “8.8.8.8”])
  • dict_keys({“router”: “192.168.1.1”, “localhost”: “127.0.0.1”, “google”: “8.8.8.8”})
  • dict_keys([‘router’, ‘localhost’, ‘google’]) (CORRECT)

Correct

CONCLUSION – Strings, Lists and Dictionaries

“In summary, this section has provided an in-depth exploration of advanced string manipulation techniques, encompassing indexing, slicing, and advanced formatting. Furthermore, you have gained insights into sophisticated data types, including lists, tuples, and dictionaries. The emphasis throughout has been on developing the skills to proficiently store, reference, and manipulate data within these structures. Moreover, the knowledge acquired here extends to integrating these data types seamlessly, empowering you to construct intricate and comprehensive data structures. Armed with these advanced techniques, you are well-prepared to tackle complex data manipulation tasks with precision and efficiency in your programming endeavors.”