CS 105 final free responses

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Create a Coord class from scratch. Objects of your class should have two instance attributes called x_coordand y_coord. Your class should have an __init__ method that takes two parameters (in addition to self) that sets the x_coord and y_coord attributes. The default values for x_coord and y_coord should both be 0. Additionally, your class should implement the __add__ method such that it returns a new Coord object where the x and y coordinates of the new object are the sum of the x and y coordinates of the two operands.

class Coord: def __init__(self, x_coord = 0, y_coord = 0): self.x_coord = x_coord self.y_coord = y_coord def __add__(self, other): return Coord(self.x_coord + other.x_coord, self.y_coord + other.y_coord)

Finish creating the Coord class. Objects of your class should have two instance attributes called x and y. Your class has an __init__ method that takes two numeric parameters (in addition to self) that sets the x and y attributes. The default values for x and y are both 0. Also, override the __str__ method such that it returns a string containing the x and y coords in the format (x, y).

class Coord: def __init__(self, x=0, y=0): self.x = x self.y = y def__str__(self): return f'({self.x}, {self.y})'

Create a Coord class from scratch. Objects of your class should have two instance attributes call x_coord and y_coord. Your class should have an __init__ method that takes two parameters (in addition to self) that sets the x_coord and y_coord attributes. The default values for x_coord and y_coord should both be 0. Additionally, your class should implement the __mul__ method such that it returns a new Coord object where the x and y coordinates of the new object are the product of the x and y coordinates of the two operands.

class Coord: def __init__(self, x_coord=0, y_coord=0) self.x_coord = x_coord self.y_coord = y_coord def __mul__(self, other): new_x = self.x_coord * other.x_coord new_y = self.y_coord * other.y_coord return Coord(new_x, new_y)

Finish creating the Coord class. Objects of your class should have two instance attributes called x_coordand y_coord. Your class has an __init__ method that takes two numeric parameters (in addition to self) that sets the x_coord and y_coord attributes. The default values for x_coord and y_coord are both 0. Also, override the __str__ method such that it returns a string containing the x_coord and y_coord coords in the format "(x_coord, y_coord)".

class Coord: def __init__(self, x_coord=0, y_coord=0) self.x_coord = x_coord self.y_coord = y_coord def __str__(self): return f'({self.x_coord}, {self.y_coord})'

Below is a working start to an (x, y) Position class that provides a constructor. Extend the class so that when a Position object is passed to the print function, that it prints the contents of the x_location attribute, a comma, and the contents of the y_location attribute. The intended way for you to do this is to override the builtin __str__ method of objects.

class Position: def ___init__(self, x_loc, y_loc): self.x_location = x_loc self.y_location = y_loc def __str__(self): self.x_location = str(self.x_location) self.y_location = str(self.y_location) return self.x_location + "," + self.y_location

Create a Roster class from scratch. Objects of your class should have a data attribute called student_names. Your class should have an __init__ method that takes a list parameter (in addition to self) that lets the student_names attribute be set. The default value for student_names should be an empty list.

class Roster: def __init__(self, student_names = []): self.student_names = student_names

Thefunction below takes two parameters: a list of numbers and an int stop. complete the function so that it appends the numbers in the range from 0 up to, but not including, stop to the list numbers. There is no need for the function to return. The recommended approach for this question is to use a for loop over a range statement.

def append_range_elements(numbers, stop): for i in range(0, stop): numbers.append(i)

The function below takes two parameters: a list numbers and an int stop. Complete the function so that it appends the numbers in the range from 0 up to, but not including, stop to the list numbers. There is no need for the function to return. The recommended approach for this question is to use a forloop over a range statement.

def append_range_elements(numbers, stop): for x in range(0, stop): numbers.append(x)

The function takes two parameters; the first is a list of strings and the second is a string name of a file. Complete the function to append the strings in lines onto the end of the file named filename, each on a new line. You'll want to open the file for appending and then you can use write function calls to complete the write. Be sure that you close the file, either with an explicit close function call or by using a with statement.

def append_strings_to_file(lines, filename): f = open(filename, 'a') for k in lines: f.write(k + '\n') f.close()

Define a function below called avg_of_a_list. The function takes one argument: a list of numbers. Complete the function so that it returns the average of the list of numbers. An empty list should have an average of zero.

def avg_of_a_list(list): if len(list) == 0: return 0 return sum(list)/len(list)

Define a function below called avg_of_a_list. The function takes one argument: a list of numbers. Complete the function so that it returns the average of the list of numbers. An empty list should have an average of zero.

def avg_of_a_list(numlist): total = 0 if len(numlist) == 0: return 0 else: for num in numlist: total += num average = total/len(numlist) return average

Write a function below, bold_word_in_paragraph, that takes two strings. The first is some paragraph or sentence, and the second is a single word. Complete the function so that it returns the original paragraph/sentence, but with the specified word surrounded by HTML bold tags. For example, if your paragraph was "Hello there! It's really great to meet you." and your word was "great", your function should return "Hello there! It's really <b>great</b> to meet you."

def bold_word_in_paragraph(paragraph, word): index = paragraph.find(word) new_paragraph = paragraph[:index] + "<b>" + word + "</b>" + paragraph[index:] return new_paragraph

The function below takes two arguments, a dictionary called dog_dictionary and a list of dog names (strings) adopted_dog_names. The dog dictionary uses dogs' names as the keys for the dictionary. Complete the function to remove all the adopted dogs from the dog_dictionary. Return the dictionary at the end of the function.

def clear_adoptions(dog_dictionary, adopted_dog_names): for dog in adopted_dog_names: if dog in dog_dictionary: del dog_dictionary[dog] return dog_dictionary

The function below takes two arguments: a dictionary called dog_dictionary and a list of dog names (strings) adopted_dog_names. The dog dictionary uses. dogs' names as the keys for the dictionary. Complete the function to remove all the adopted dogs from the dog_dictionary. Return the dictionary at the end of the function.

def clear_adoptions(dog_dictionary, adopted_dog_names): for name in adopted_dog_names: if name in dog_dictionary: dog_dictionary.pop(name) return dog_dictionary

The function below takes one parameter list1, which is a list of strings. Complete the function so that it returns a new string that is the concatenation of the first three strings in the list. For example: concatenate_three_strings(['CS', '105', 'is', 'awesome']) should return 'CS105is'

def concatenate_three_strings(list1): new_string = list1[0] + list1[1] + list1[2] return new_string

Define a function below called count_candy. The function takes a single argument of type list of strings. Each string in the list is the name of a candy. Complete the function so that it returns a dictionary of key: value pairs, where each key is a string that is the name of a candy and the count is how often that candy appears in the list.

def count_candy(list): dict = {} for candy in list: if candy in dict: dict[candy] += 1 elif candy not in dict: dict[candy] = 1 return dict

Create a function count_num_vowels that takes a single parameter (s) which is a single string. Complete the function such that it returns a count of the number of vowels present in the string. For this exercise you can assume that all strings are lower case. For the purpose of this question, 'y' is not a vowel.

def count_num_vowels(s): vowels = 'aeiou' vowel_count = 0 for elem in s: if elem in vowels: vowel_count += 1 return vowel_count

The function below takes two parameters: a list of strings (str_list) and an string (substr). Complete the function to return a count of how many of the strings in the list have substras a substring. All of the strings will be lower case, so you don't need to worry about case for this question. For example, the substring 's h' can be found in the string 'is here', but not in 'not here'.

def count_strings_containing_substring(str_list, substr): count = 0 for string in str_list: if substr in string: count += 1 return count

The function below takes one parameter: a list, that contains only strings. Complete the function to create an ordered HTML list, as a string, and returns it. An empty list should return an empty HTML list with no list items. Do not add any extraneous whitespace to the HTML.

def create_ordered_list(str_list): html = "" html += "<ol>" for i in str_list: html += "<li>" + i + "</li>" html += "</ol>" return html

The function below takes one parameter: a list, that contains only strings. Complete the function to create a ordered HTML list, as a string, and returns it. An empty list should return an empty HTML list with no list items. Do not add any extraneous whitespace to the HTML. For example, if given the list ["one", "two"], the function should return "<ol><li>one</li><li>two</li></ol>".

def create_ordered_list(str_list): newstr = "<ol>" if len(str_list) == 0 return "<ol></ol>" else: for x in str_list: newstr += "<li>" + x + "</li>" newstr += "</ol>" return newstr

For the function below, a comma separated string is passed in as the argument csv_ints. From that string, create and return a new comma separated string with each value squared. For instance, given the string "1,2,3" the string "1,4,9" should be returned.

def csv_squared(cdv_ints): new_list = cdv_ints.split(',') for x in range(len(new_list)): new_list[x] = int(new_list[x]) new_list[x] = pow(new_list[x], 2) new_list[x] = str(new_list[x]) newstr = ','.join(new_list) return newstr

Define a function below called decrease_elements_by_x, which takes two arguments - a list of numbers and a single positive number (you might want to call it x). Complete the function such that it returns a copy of the original list where every value is decreased by the second argument. For example, given the inputs [1, 2, 5] and 2, your function should return [-1, 0, 3].

def decrease_elements_by_x(list, x): new = [] for num in list: num -= x new.append(num) return new

Define a function below called decrease_elements_by_x, which takes two arguments - a list of numbers and a single positive number (you might want to call it x). Complete the function such that it returns a copy of the original list where every value is decreased by the second argument. For example, given the inputs [1,2,5] and 2, your function should return [-1,0,3].

def decrease_elements_by_x(list, x): new_list = list new_list2 = [] for elem in new_list: elem -= x new_list2.append(elem) return new_list2

The function below takes one parameter: a string (date_string) containing a date in the mm/dd/year format. Complete the function to return a list containing integers for each of the date components in month, day, year order. For example, if given the string '06/11/1930', your code should return the list [6, 11, 1930].

def extract_data_components(date_string): words = date_string.split('/') return [int(words[0]), int(words[1]), int(words[2])]

The function below takes one parameter: a string (date_string) containing a date in the mm/dd/year format. Complete the function to return a list containing integers for each of the date components in month, day, year order. For example, if given the string '06/11/1930', your code should return the list [6, 11, 1930].

def extract_date_components(date_string): date_list = [] split = date_string.split('/') for date in date_list: date_list.append(int(date)) return date_list

Define a new function below, filter_list, which takes two arguments: a list and a number. The list can contain numbers and strings. Complete the function to return only strings whose lengths are multiples of the number argument. For example, if the input list is ["Fish", 5, "Bannerlord", "Hello"] and input number is 2, then the output should be ["Fish", "Bannerlord"]. It is okay to return an empty list if the filter keeps no elements.

def filter_list(list, num): list2 = [] for value in list: if type(value) == str: if len(value) % num == 0: list2.append(value) return list2

Define a new function below, filter_list, which takes two arguments: a list and a number. The list can contain numbers and strings. Complete the function to return any strings and only numbers (i.e. ints or floats) which are not multiples of the number argument. For example, if the input list is ["Spartacus", 4.0, 5, 2] and input number is 2, then the output should be ["Spartacus", 5]. It is okay to return an empty list if the filter keeps no elements.

def filter_list(list, number): new_list = [] for elem in list: if type(elem) == str: new_list.append(elem) else: if elem % number != 0: new_list.append(elem) return new_list

The function below takes one parameter: a list of numbers (info_list). Complete the function to return a new list containing only the negative numbers from the original list.

def filter_negatives(info_list): list = [] for num in info_list: if num < 0: list.append(num) return list

The function below takes a single argument: data_list, a list containing a mix of strings and numbers. The function currently uses the Filter pattern to filter the list in order to return a new list which contains only strings longer than five characters. You should modify it such that it uses the Filter pattern to instead return a new list containing only positive (that is, greater than 0) integers from the data_list.

def filter_on_a_condition(data_list): new_list = [] for data in data_list: if type(data) == int and data > 0: new_list.append(data) return new_list

Create a function filter_strs_with_even_vowel_count that take a single parameter(str_li) which is a list of strings. Complete the function such that it returns a list with only strings that contain an even number of vowels (i.e., 'aeiou'). For these tests you can assume that all characters in the strings are lower case.

def filter_strs_with_even_vowel_count(str_li): vow = 'aeiou' lst = [] for val in str_li: v = 0 for l in val: if l in vow: v += 1 if v % 2 == 0: lst.append(val) return lst

The function below takes a single string parameter last_name. Complete the function using the table below to return the correct string indicating which room a person should go to based on their last name. (A - G) --> 'NOYES 100' (H - Q) --> 'DKH 114' (R - Z) --> 'BEV 180'

def finals_room(last_name): for name in last_name: if name[0] >= 'A' and name [0] <= 'G': return 'NOYES 100' elif name[0] >= 'H' and name[0] <= 'Q': return 'DKH 114' elif name[0] >= 'R' and name[0] <= 'Z': return 'BEV 180'

The function below takes one parameter: a list (a_list) that can contain integers, floats, and strings in any order. Complete the function to return the largest number from the list.

def find_largest_num_mixed_list(a_list): largest_number = -10000000 for elem in a_list: if type(elem) == int or type(elem) == float: if elem > largest_number: largest_number = elem return largest_number

The function below takes one parameter: a list (string_list) that contains only strings. Complete the function to return the longest string from the list. If the list is empty, return an empty string (i.e "").

def find_longest_string(string_list): longest_string = "" for string in string_list: if len(string) > len(longest_string): longest_string = string return longest_string

The function below takes a list of strings as an argument, string_inputs. The function finds the first string in the list with an even length and then return that string. If no even length string is found, it returns an empty string "". Modify the code to return the last string in the list with an even length.

def find_str(string_inputs): new_list = [] for val in string_inputs: if len(val) % 2 == 0: new_list.append(val) return new_list[-1]

The function below tries to read a whole number (i.e., an integer) from the user and return it as an integer to its caller. This works great as long as what the the user types is a whole number. If the user types a non-integer number of a collection of letters, this code will fail when it tries to convert it to an integer. Fix this code so that it returns None instead of raising an exception. Do this with try/except blocks.

def get_an_input_integer(): in_string = input('Enter your favorite whole number: \n') try: in_integer = int(in_string) except: return None return in_integer

The function below takes a list of strings, shopping_cart, and a dictionary with strings as keys and floating points as values, price_lookup, as parameters. Use a loop to iterate over the values in shopping cart to lookup the prices in price_lookup and append them to a new list. Finally, return the new list as if it were a receipt for all the items in the shopping cart.

def get_receipt(shopping_cart, price_lookup): receipt = [] for item in shopping_cart: price = lookup.get(item) receipt.append(price) return receipt

The function below takes a single string parameter: sentence. Complete the function to return a list of strings that are in the sentence that contain a lowercase letter 'a'.

def get_strings__with_letter_a(sentence) list = sentence.split() list2 = [] for elem in list: if 'a' in elem: list2.append(elem_ return list2

Write a Python function from scratch called has_3_or_more_elements that takes a single list parameter. Your function should return a Boolean. The return value should be True if the list parameter has 3 or more elements and Falseotherwise.

def has_3_or_more_elements(list): if len(list) >= 3: return True else: return False

The function below takes two string parameters: sentence is a string containing a series of words separated by whitespace and letter is a string containing a single lower case letter. It is supposed to return a string containing one of the words in sentence that contains letter (in either upper case or lower case) while retaining the original capitalization. Can you fix it?

for extract_word_with_given_letter(sentence, letter): temp = sentence.split() for w in temp: if letter.upper() in w or letter.lower() in w: return w

The function takes a single parameter: the name of a file. The file contains integers, with one positive integer per line, none of which are larger than 100. Currently, the file returns the largest number in the file. Can you modify the function such that it returns the number and the line it appeared on? For example, if the largest number is 20 and it appears on line 5, return the string "20 5". You should start counting lines at 1, not 0.

def num_in_file(filename): fpoint = open(filename, "r") numbers = fpoint.readlines() largest_num = -1 lines = 0 for data in numbers: if int(data) > largest_num: largest_num = int(data) lines += 1 return f'{largest_num} {lines}'

The function takes a single parameter: the name of a file. The file contains integers, with one positive integer per line, none of which are larger than 100. Currently, the file returns the largest number in the file. Can you modify the function such that it returns the smallest number in the file instead?

def num_in_file(filename): fpoint = open(filename, "r") numbers = fpoint.readlines() smallest_num = 101 for data in numbers: if int(data) < smallest_num: smallest_num = int(data) return smallest_num

Define a function below, posodd_number_filter, which takes a single numerical argument. Complete the function to return Trueif the input is positive and odd. Otherwise, return False.

def posodd_number_filter(num): if num > 0 and (num % 2 != 0): return True else: return False

Define a function below, posodd_number_filter, which takes a single numerical argument. Complete the function to return True if the input is positive and odd. Otherwise, return False.

def posodd_number_filter(number): if number > 0 and number % 2 != 0: return True else: return False

Write a Python function called print_nested_list that takes a single parameter, a list of lists of strings. Complete the function as follows: 1. Each list of strings should be printed with a single space between each string, all on the same line 2. Each list of strings should be printed on its own line

def print_nested_list(list_of_lists): for list in list_of_lists: line = ' '.join(list) print(line)

The function below takes two parameters: a dictionary (dictionary) that maps strings (keys) to strings (values) and a string key. Complete the function so that it prints out the value stored in the dictionary associated with the given key. You should use the default form of the print function that includes the newline.

def print_single_dict_value(dictionary, key): if key in dictionary: print(dictionary[key])

The function below takes a single argument, a string called personal_data with a subset of someone's personal data. Somewhere in the string will be an email address of random length, surrounded by angle brackets like "<[email protected]>". Complete the function to return just the email address from the string of personal information.

def return_isolated_data(personal_data): open = personal_data.find('<') close = personal_data.find('>') email = personal_data[open+1 : close] return email

The function below takes a single argument, a string called personal_data with a subset of someone's personal data. Somewhere in the string will be an email address of random length, surrounded by angle brackets, like "<[email protected]>". Complete the function to return just the email address from the string of personal information.

def return_isolated_data(personal_data): start = personal_data.find("<") end = personal_data.find(">") email = personal_data[start+1:end] return email

In the function below, return the (single) element from the input list input_list which is in the second to last position in the list. Assume that the list is large enough.

def return_second_to_last_element(input_list): return input_list[-2]

The function below takes one parameter: a list of strings (string_list). Complete the function to return a new list containing only the strings from the original list that are more than 20 characters long.

def select_long_strings(string_list): new_list = [] for elem in string_list: if len(elem) > 20: new_list.append(elem) return new_list

The function below takes one parameter: a list of strings (string_list). Complete the function to return a new list containing only the strings from the original list that are less than 20 characters long.

def select_short_strings(string_list): new_list = [] for string in string_list: if len(string) < 20: new_list.append(string) return new_list

The function below takes one parameter: a list of strings (string_list). Complete the function to return a new list containing only the strings from the original list that are before the first empty string in the list.

def select_strings_upto_empty_string(string_list): new_list = [] for string in string_list: if string != "": new_list.append(string) else: break return new_list

The function below takes one parameter: a list of strings (string_list). Complete the function to return a new list containing only the strings from the original list that contain at least 5 words. You can assume that there is white space separating each pair of words in a string.

def select_strings_with_at_least_5_words(string_list): new_list = [] for string in string_list: new_list2 = string.split() if len(new_list2) >= 5: new_list.append(string) return new_list

The function below takes one parameter: a list of strings (string_list). Complete the function to return a new list containing only the strings from the original list that contain at least 5 words. You can assume that there is white space separating each pair of words in a string.

def select_strings_with_at_least_5_words(string_list): new_list = [] for string in string_list: new_string_list = string.split() if len(new_string_list) >= 5: new_list.append(string) return new_list

The function below takes two string arguments: word and text. Complete the function to return whichever of the strings is shorter. You don't have to worry about the case where the strings are the same length.

def shorter_string(word, text): if len(word) < len(text): return word else: return text

In the function below, return the string 'negative' if the numeric parameter number is in fact negative, or, return the string 'positive' if the parameter number is positive, otherwise return string 'zero'

def string_indicating_positivityOrNegativity(number): if number < 0: return 'negative' elif number > 0: return 'positive' else: return 'zero'

If you have a list consisting of just numbers, then you can add all of the values in the list using the sum() function. If your list consists of some numbers and some values of other types (e.g., lists, strings, sets), the sum() function will fail. In this question, we're asking you to write a function that will sum all of the numbers in a list, ignoring the non-numbers. The function below takes one parameter: a list of values (info) of various types.

def sum_lenths(info): sum = 0 for elem in info: if type(elem) == int or type(elem) == float: sum += elem return sum

Write a function called sum_up_to_n that takes a single positive integer parameter. The function should also return a positive integer. In particular, it should return the sum of the positive integers from 1 to the value passed into the function. For example, if 5 is passed into the function, it should return 15because that is the number you get when you add 1 + 2 + 3 + 4 + 5.

def sum_up_to_n(num): sum = 0 for val in range(num + 1): sum += val return sum

The function below, keep_only_some, takes two arguments: the list data and the number multiple. The list can contain numbers and strings. Complete the function to return only numbers (i.e. ints or floats) which are multiples of the number argument. For example, if the input list is [8, 3, "Butterlord", 10] and input number is 2, then the output should be [8, 10]. It is okay to return an empty list if the filter keeps no elements.

def keep_only_some(data, multiple): new_list = [] for elem in data: if type(elem) == int or type(elem) == float: if elem % multiple == 0: new_list.append(elem) return new_list

The function below takes a single string parameter: input_list. If the input list contains the lowercase letter z, return the string 'has the letter z'. Otherwise, return the string 'no z found'.

def list_contains(input_list): if 'z' in input_list: return 'has the letter z' else: return 'no z found'

Define a function below called make_list_from_args, which takes four numerical arguments. Complete the function to return a list which contains only the even numbers - it is acceptable to return an empty list if all the numbers are odd.

def make_list_from_args(num1, num2, num3, num4): new = [] if num1 % 2 == 0: new.append(num1) if num2 % 2 == 0: new.append(num2) if num3 % 2 == 0: new.append(num3) if num4 % 2 == 0: new.append(num4) return new

The function below takes one parameter: a string called data_str that contains a series of values in Comma Separated Values format. Complete the function to return the maximum value of the collection of values. The numbers in the CSV will be in the range -1000 to 1000. To complete this question you'll need to split the CSV into a list and convert the resulting strings into floats.

def maximum_from_CSV(data_str): return max(list(map(float, data_str.split(','))))

Your friend just came back from a weekend hike and they excitedly gave you a Python list of birds they saw on their trip. Unfortunately, they were not careful about their notes, having things such as "sparrow" and "SpARROW" written down originally. They want you to write a function which takes this disorganized list of bird names as an input and returns just a list of the unique bird species they saw. Please make all the strings lower case.

def unique_bird_log(exciting_birds): new_list = [] for bird in exciting_birds: if bird.lower() not in new_list: new_list.append(bird.lower()) return new_list

Define a function below, update_dict_with_rules, which takes two arguments: both are a dictionary of strings (keys) to integers (values). Complete the function such that it updates the first dictionary as follows: - For key-value pairs in both dictionaries, subtract the second dictionary's value from the first's - For key-value pairs in the second dictionary only, insert them into the first - Make no changes to key-value pairs unique to the first dictionary These updates should be made in-place: do not return anything from the function!

def update_dict_with_rules(dict1, dict2): for x in dict2: if x in dict1: dict1[x] = dict1[x] - dict2[x] elif x not in dict1: dict1[x] = dict2[x]


संबंधित स्टडी सेट्स

Ch 21 Respiratory Care Modalities

View Set

History unit #1 confederation of canada

View Set