Spread the love

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.

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 ___:

# 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 = ___

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 ___:

# If True, the “input_string” contains a palindrome.

return True

# Otherwise, return False.

return False

print(is_palindrome(“Never Odd or Even”)) # Should be True

print(is_palindrome(“abc”)) # Should be False

print(is_palindrome(“kayak”)) # Should be True

  • 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 += letter.lower()

reverse_string = letter.lower() + 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 == reverse_string:

# If True, the “input_string” contains a palindrome.

return true

# Otherwise, return False.

return false

print(is_palindrome(“Never Odd or Even”)) # Should be True

print(is_palindrome(“abc”)) # Should be False

print(is_palindrome(“kayak”)) # Should be True

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”.

def convert_distance(miles):

km = miles * 1.6

result = “{} miles equals {___} 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

  • 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

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])
  • print(Weather[4:])
  • print(Weather[1:4])
  • print(Weather[:”f”])

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.”

def nametag(first_name, last_name):

return(“___.”.format(___))

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.”

  • 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.”

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).

def replace_ending(sentence, old, new):

# Check if the old substring is at the end of the sentence

if ___:

# 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 = ___

new_sentence = ___

return new_sentence

# Return the original sentence if there is no match

return sentence

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”

  • def replace_ending(sentence, old, new):

# Check if the old substring is at the end of the sentence

if sentence.endswith(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

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”

6. Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = [“program.c”, “stdio.hpp”, “sample.hpp”, “a.out”, “math.hpp”, “hpp.out”]

# Generate newfilenames as a list containing the new filenames

# using as many lines of code as your chosen method requires.

___

print(newfilenames)

# Should be [“program.c”, “stdio.h”, “sample.h”, “a.out”, “math.h”, “hpp.out”]

  • filenames = [“program.c”, “stdio.hpp”, “sample.hpp”, “a.out”, “math.hpp”, “hpp.out”]

newfilenames = []

for name in filenames:

if name.endswith(“hpp”):

newname = name[:-3] + “h”

else:

newname = name

newfilenames.append(newname)

print(newfilenames)

# Should be [“program.c”, “stdio.h”, “sample.h”, “a.out”, “math.h”, “hpp.out”]

7. Let’s create a function that turns text into pig latin: a simple text transformation that modifies each word moving the first character to the end and appending “ay” to the end. For example, python ends up as ythonpay.

def pig_latin(text):

say = “”

# Separate the text into words

words = ___

for word in words:

# Create the pig latin word and add it to the list

___

# Turn the list back into a phrase

return ___

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”

  • def pig_latin(text):

say = “”

# Separate the text into words

words = text.split()

piglatin_words = []

for word in words:

# Create the pig latin word and add it to the list

piglatin_word = word[1:] + word[0] + “ay”

piglatin_words.append(piglatin_word)

# Turn the list back into a phrase

say = ” “.join(piglatin_words)

return say

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”

8. The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with 4 corresponding to read, 2 to write, and 1 to execute. Or it can be written with a string using the letters r, w, and x or – when the permission is not granted. For example: 640 is read/write for the owner, read for the group, and no permissions for the others; converted to a string, it would be: “rw-r—–” 755 is read/write/execute for the owner, and read/execute for group and others; converted to a string, it would be: “rwxr-xr-x” Fill in the blanks to make the code convert a permission in octal format into a string format.

def octal_to_string(octal):

result = “”

value_letters = [(4,”r”),(2,”w”),(1,”x”)]

# Iterate over each of the digits in octal

for ___ in [int(n) for n in str(octal)]:

# Check for each of the permissions values

for value, letter in value_letters:

if ___ >= value:

result += ___

___ -= value

else:

___

return result

print(octal_to_string(755)) # Should be rwxr-xr-x

print(octal_to_string(644)) # Should be rw-r–r–

print(octal_to_string(750)) # Should be rwxr-x—

print(octal_to_string(600)) # Should be rw——-

  • def octal_to_string(octal):

result = “”

value_letters = [(4,”r”),(2,”w”),(1,”x”)]

# Iterate over each of the digits in octal

for digit in [int(n) for n instr(octal)]:

# Check for each of the permissions values

for value, letter in value_letters:

if digit >= value:

result += letter

digit -= value

else:

result += “-“

return result

 

print(octal_to_string(755)) # Should be rwxr-xr-x

print(octal_to_string(644)) # Should be rw-r–r–

print(octal_to_string(750)) # Should be rwxr-x—

print(octal_to_string(600)) # Should be rw——-

Advertisement

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

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

10. The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, … For example, group_list(“g”, [“a”,”b”,”c”]) returns “g: a, b, c”. Fill in the gaps in this function to do that.

def group_list(group, users):

members = ___

return ___

print(group_list(“Marketing”, [“Mike”, “Karen”, “Jake”, “Tasha”]))

# Should be “Marketing: Mike, Karen, Jake, Tasha”

print(group_list(“Engineering”, [“Kim”, “Jay”, “Tom”]))

# Should be “Engineering: Kim, Jay, Tom”

print(group_list(“Users”, “”)) # Should be “Users:”

  • def group_list(group, users):

members = “, “.join(users)

return”{}: {}”.format(group, members)

print(group_list(“Marketing”, [“Mike”, “Karen”, “Jake”, “Tasha”])) # Should be “Marketing: Mike, Karen, Jake, Tasha”

print(group_list(“Engineering”, [“Kim”, “Jay”, “Tom”])) # Should be “Engineering: Kim, Jay, Tom”

print(group_list(“Users”, “”)) # Should be “Users:”

11. The email_list function receives a dictionary, which contains domain names as keys, and a list of users as values. Fill in the blanks to generate a list that contains complete email addresses (e.g. diana.prince@gmail.com).

def email_list(domains):

emails = []

for ___:

for user in users:

emails.___

return(emails)

print(email_list({“gmail.com”: [“clark.kent”, “diana.prince”, “peter.parker”], “yahoo.com”: [“barbara.gordon”, “jean.grey”], “hotmail.com”: [“bruce.wayne”]}))

  • def email_list(domains):

emails = []

for domain, users in domains.items():

for user in users:

emails.append(user + “@” + domain)

return(emails)

print(email_list({“gmail.com”: [“clark.kent”, “diana.prince”, “peter.parker”], “yahoo.com”: [“barbara.gordon”, “jean.grey”], “hotmail.com”: [“bruce.wayne”]}))

12. The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values.

def groups_per_user(group_dictionary):

user_groups = {}

# Go through group_dictionary

for ___:

# Now go through the users in the group

for ___:

# Now add the group to the the list of

# groups for this user, creating the entry

# in the dictionary if necessary

return(user_groups)

print(groups_per_user({“local”: [“admin”, “userA”],

“public”: [“admin”, “userB”],

“administrator”: [“admin”] }))

  • def groups_per_user(group_dictionary):

user_groups = {}

# Go through group_dictionary

for group, users in group_dictionary.items():

# Now go through the users in the group

for user in users:

# Now add the group to the the list of groups for this user, creating the entry in the dictionary if necessary

if user notin user_groups:

user_groups[user] = []

user_groups[user].append(group)

return user_groups

print(groups_per_user({“local”: [“admin”, “userA”],

“public”: [“admin”, “userB”],

“administrator”: [“admin”] }))

13. The dict.update method updates one dictionary with the items coming from the other dictionary, so that existing entries are replaced and new entries are added. What is the content of the dictionary “wardrobe“ at the end of the following code?

wardrobe = {‘shirt’: [‘red’, ‘blue’, ‘white’], ‘jeans’: [‘blue’, ‘black’]}

new_items = {‘jeans’: [‘white’], ‘scarf’: [‘yellow’], ‘socks’: [‘black’, ‘brown’]}

wardrobe.update(new_items)

  • {‘jeans’: [‘white’], ‘scarf’: [‘yellow’], ‘socks’: [‘black’, ‘brown’]}
  • {‘shirt’: [‘red’, ‘blue’, ‘white’], ‘jeans’: [‘white’], ‘scarf’: [‘yellow’], ‘socks’: [‘black’, ‘brown’]}
  • {‘shirt’: [‘red’, ‘blue’, ‘white’], ‘jeans’: [‘blue’, ‘black’, ‘white’], ‘scarf’: [‘yellow’], ‘socks’: [‘black’, ‘brown’]}
  • {‘shirt’: [‘red’, ‘blue’, ‘white’], ‘jeans’: [‘blue’, ‘black’], ‘jeans’: [‘white’], ‘scarf’: [‘yellow’], ‘socks’: [‘black’, ‘brown’]}

14. What’s a major advantage of using dictionaries over lists?

  • Dictionaries are ordered sets
  • Dictionaries can be accessed by the index number of the element
  • Elements can be removed and inserted into dictionaries
  • It’s quicker and easier to find a specific element in a dictionary

15. The add_prices function returns the total price of all of the groceries in the dictionary. Fill in the blanks to complete this function.

def add_prices(basket):

# Initialize the variable that will be used for the calculation

total = 0

# Iterate through the dictionary items

for ___:

# Add each price to the total calculation

# Hint: how do you access the values of

# dictionary items?

total += ___

# Limit the return value to 2 decimal places

return round(total, 2)

groceries = {“bananas”: 1.56, “apples”: 2.50, “oranges”: 0.99, “bread”: 4.59,

“coffee”: 6.99, “milk”: 3.39, “eggs”: 2.98, “cheese”: 5.44}

print(add_prices(groceries)) # Should print 28.44

  • def add_prices(basket):

# Initialize the variable that will be used for the calculation

total = 0

# Iterate through the dictionary items

for item in basket:

# Add each price to the total calculation

# Hint: how do you access the values of

# dictionary items?

total += basket[item]

# Limit the return value to 2 decimal places

returnround(total, 2)

groceries = {“bananas”: 1.56, “apples”: 2.50, “oranges”: 0.99, “bread”: 4.59,

“coffee”: 6.99, “milk”: 3.39, “eggs”: 2.98, “cheese”: 5.44}

print(add_prices(groceries)) # Should print 28.44

16. 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”.

17. Fill in the blank to complete the “string_words” function. This function should split up the words in the given “string” and return the number of words in the “string”. Complete the string operation and method needed in this function so that a function call like “string_words(“Hello, World”)” will return the output “2”.

def string_words(string):

# Complete the return statement using both a string operation and

# a string method in a single line.

return ___

print(string_words(“Hello, World”)) # Should print 2

print(string_words(“Python is awesome”)) # Should print 3

print(string_words(“Keep going”)) # Should print 2

print(string_words(“Have a nice day”)) # Should print 4

  • def string_words(string):

# Complete the return statement using both a string operation and

# a string method in a single line.

returnlen(string.split())

print(string_words(“Hello, World”)) # Should print 2

print(string_words(“Python is awesome”)) # Should print 3

print(string_words(“Keep going”)) # Should print 2

print(string_words(“Have a nice day”)) # Should print 4

18. 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:

1. accept two lists through the function’s parameters;,

2. combine the two lists;

3. sort the combined list in alphabetical order;

4. return the new list.

def alphabetize_lists(list1, list2):

new_list = ___ # Initialize a new list.

___ # Combine the lists.

___ # Sort the combined lists.

new_list = ___ # Assign the combined lists to the “new_list”.

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’]

  • def alphabetize_lists(list1, list2):

new_list = list1 + list2 # Combine the two lists using the ‘+’ operator.

new_list.sort() # Sort the combined list using the ‘sort()’ method.

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’]

19. Fill in the blank to complete the “squares” function. This function should use a list comprehension to create a list of squared numbers (using either the expression n*n or n**2). The function receives two variables and should return the list of squares that occur between the “start” and “end” variables 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, 9]”.

def squares(start, end):

return [ ___ ] # Create the required list comprehension.

print(squares(2, 3)) # Should print [4, 9]

print(squares(1, 5)) # Should print [1, 4, 9, 16, 25]

print(squares(0, 10)) # Should print [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

  • def squares(start, end):

return [n*n for n inrange(start, end+1)] # Create the required list comprehension.

print(squares(2, 3)) # Should print [4, 9]

print(squares(1, 5)) # Should print [1, 4, 9, 16, 25]

print(squares(0, 10)) # Should print [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

20. Fill in the blanks to complete the “car_listing” function. This function accepts a “car_prices” dictionary. It should iterate through the keys (car models) and values (car prices) in that dictionary. For each item pair, the function should format a string so that a dictionary entry like ““Kia Soul“:19000” will print “A Kia Soul costs 19000 dollars”. Each new string should appear on its own line.

def car_listing(car_prices):

result = “”

# Complete the for loop to iterate through the key and value items

# in the dictionary.

for __

result += ___ # Use a string method to format the required string.

return result

print(car_listing({“Kia Soul”:19000, “Lamborghini Diablo”:55000,

“Ford Fiesta”:13000, “Toyota Prius”:24000}))

# Should print:

# A Kia Soul costs 19000 dollars

# A Lamborghini Diablo costs 55000 dollars

# A Ford Fiesta costs 13000 dollars

# A Toyota Prius costs 24000 dollars

  • def car_listing(car_prices):

result = “”

# Complete the for loop to iterate through the key and value items

# in the dictionary.

for car, price in car_prices.items():

result += “A {} costs {} dollars\n”.format(car, price) # Use a string method to format the required string.

return result

print(car_listing({“Kia Soul”:19000, “Lamborghini Diablo”:55000, “Ford Fiesta”:13000, “Toyota Prius”:24000}))

# Should print:

# A Kia Soul costs 19000 dollars

# A Lamborghini Diablo costs 55000 dollars

# A Ford Fiesta costs 13000 dollars

# A Toyota Prius costs 24000 dollars

21. 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:

1. accept two dictionaries through the function’s parameters;

2. combine both dictionaries into one, with each key listed only once;

3. the values from the “guests1” dictionary taking precedence, if a key is included in both dictionaries;

4. then print the new dictionary of combined items.

def combine_guests(guests1, guests2):

___ # Use a dictionary method to combine the dictionaries.

return guests2

Ricks_guests = { “Adam”:2, “Camila”:3, “David”:1, “Jamal”:3, “Charley”:2,

“Titus”:1, “Raj”:4}

Tessas_guests = { “David”:4, “Noemi”:1, “Raj”:2, “Adam”:1, “Sakira”:3, “Chidi”:5}

print(combine_guests(Ricks_guests, Tessas_guests))

# Should print:

# {‘David’: 1, ‘Noemi’: 1, ‘Raj’: 4, ‘Adam’: 2, ‘Sakira’: 3, ‘Chidi’: 5, ‘Camila’: 3,

‘Jamal’: 3, ‘Charley’: 2, ‘Titus’: 1}

22. 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:

1. accept a string “text” variable through the function’s parameters;

2. initialize an new dictionary;

3. iterate over each text character to check if the character is a number’

4. count the frequency of numbers in the input string, ignoring all other characters;

5. 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;

6. return the new dictionary.

23. What do the following commands return when animal = “Hippopotamus”?

print(animal[3:6])

print(animal[-5])

print(animal[10:])

  • pop, t, us
  • ppop, o, s
  • popo, t, mus
  • ppo, t, mus

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

music_genres = [“rock”, “pop”, “country”]

music_genres.append(“blues”)

  • [‘rock’, ‘pop’, ‘blues’]
  • [‘rock’, ‘blues’, ‘country’]
  • [‘rock’, ‘blues’, ‘pop’, ‘country’]
  • [‘rock’, ‘pop’, ‘country’, ‘blues’]

25. What do the following commands return?

teacher_names = {“Math”: “Aniyah Cook”, “Science”: “Ines Bisset”,

“Engineering”: “Wayne Branon”}

teacher_names.values()

  • [‘Aniyah Cook’, ‘Ines Bisset’, ‘Wayne Branon”]
  • [“Math”, “Aniyah Cook”, “Science”, “Ines Bisset”, “Engineering”, “Wayne Branon”]
  • dict_values([‘Aniyah Cook’, ‘Ines Bisset’, ‘Wayne Branon’])
  • {“Math”: “Aniyah Cook”,”Science”: “Ines Bisset”, “Engineering”: “Wayne Branon”}

26. 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”.

27. 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.

28. 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]”.

29. Fill in the blanks to complete the “endangered_animals” function. This function accepts a dictionary containing a list of endangered animals (keys) and their remaining population (values). For each key in the given “animal_dict” dictionary, format a string to print the name of the animal, with one animal name per line.

30. Consider the following scenario about using Python dictionaries:

Tessa and Rick are hosting a party. Together, they sent out invitations, and collected the responses in a dictionary, with names of their friends and the number of guests each friend will be bringing.

Complete the function so that the “check_guests” function retrieves the number of guests (value) the specified friend “guest” (key) is bringing. This function should:

1. accept a dictionary “guest_list” and a key “guest” variable passed through the function parameters;

2. print the values associated with the key variable.

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

1. print(genre[:-8])

2. print(genre[-7:9])

  • transc, nd
  • endental, tr
  • dental, trans
  • ran, ental

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

1. car_makes = [“Ford”, “Volkswagen”, “Toyota”]

2. car_makes.remove(“Ford”)

  • [null, ‘Porsche’, ‘Toyota’]
  • [‘Toyota’, ‘Ford’]
  • [‘Volkswagen’, ‘Toyota’]
  • [”, ‘Porsche’, ‘Vokswagen’, ‘Toyota’]

33. What do the following commands return?

1. speed_limits = {“street”: 35, “highway”: 65, “school”: 15}

2. speed_limits[“highway”]

  • [65]
  • {“highway”: 65}
  • 65
  • [“highway”, 65]

34. Fill in the blank to complete the “first_character” function. This function should return the first character of any string passed in. Complete the string operation needed in this function so that input like “Hello, World” will produce the output “H”.

35. 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.

36. 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({“router”: “192.168.1.1”, “localhost”: “127.0.0.1”, “google”: “8.8.8.8”})
  • 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’, ‘localhost’, ‘google’])

37. 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.

38. 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:

1. accept a string through the parameters of the function;

2. separate the address string into new strings: house_number and street_name;

3. return the variables in the string format: “House number X on a street named Y”.

39. 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:

1. accept a string “text” variable through the function’s parameters;

2. 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);

3. 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;

4. return the new dictionary.

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

colors = [“red”, “white”, “blue”]
colors.insert(2, “yellow”)

  • [‘red’, ‘white’, ‘yellow’]
  • [‘red’, ‘yellow’, ‘blue’]
  • [‘red’, ‘white’, ‘yellow’, ‘blue’]
  • [‘red’, ‘yellow’, ‘white’, ‘blue’]

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *