CS Test 3
Define a function below called write_avg_to_file. The function takes one argument: a list of numerical data. Complete the function so that it writes the average of the list to the file output_file.txt. You should not write a newline after the average.
def write_avg_to_file(list): file = open("output_file.txt","w") total = 0 for i in list: total += i avg = total/len(list) avg = str(avg) file.write(avg)
A computer's CPU executes instructions that are written in: (a) the CPU only executes 0s and 1s (b) a subset of the English language (c) Python (d) source code
(a) the CPU only executes 0s and 1s
Before reading or writing to a file, a file object must be created via (a) File (b) create (c) open (d) Folder
(c) open
A statement is: (a) a translation of machine language (b) a precise description of a problem (c) a section of an algorithm (d) a complete computer command
(d) a complete computer command
Multi-way decisions must be handled by nesting multiple if-else statements.
False
Write a statement that creates a dictionary that associates the following cities with their 2010 population and assign it to a variable named city_populations. Danville 33027 Mount Prospect 54167
city_populations = {"Danville" : 33027 , "Mount Prospect" : 54167}
Write a statement that creates a new list called countries_sorted that is a sorted version of the list countries, without changing the list countries.
countries_sorted = sorted(countries)
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): with open(filename, 'a') as f: for line in lines: f.write(line + "\n")
The function below takes one parameter: a list of integers (my_list). Complete the function to count how many of the numbers in the list are even. As discussed in lecture, this question uses the 'visit every element of a collection' pattern, the 'is a number even' pattern, and the 'count' pattern.
def count_even_number(num_list): count = 0 for i in num_list: if i%2 == 0: count += 1 return count print(count_even_number([10, 33, 53, 45, 7, 6]))
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(data): html_list="" html_list+="<ol>" for i in data: html_list+="<li>"+i+"</li>" html_list+="</ol>" return html_list
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]. increase.py
def decrease_elements_by_x(lst,x): for i in range(len(lst)): lst[i]=lst[i]-x return lst print(decrease_elements_by_x([1,2,5],2))
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_condition(data_lst): 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 takes 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 fitler_strs_with_even_vowel_count(str_li): result = [] for string in str_list: vowel_count = 0 for c in string: if c in "aeiou": vowel_count =+ 1 if vowel_count % 2 == 0: result.append(string) return result
Define a function below, get_netid, which takes a string argument (an email address) as an argument. Email addresses will be passed in using the format '[email protected]'. Complete the function to return the netid part of the email address (i.e., the part before the @ symbol) as a string. For example, your code should return 'xxxx' if given the email address above. Hint: to find the end point for slicing either use the find function or use negative indexing.
def get_netid(email): index = email.find('@') id = email[:index] return id
Write a statement that takes a variable named f that contains a writeable file object and writes into it the contents of the variable data_item.
f.write(data_item)
In HTML, elements using <heading> tags are used to provide titles to sections.
false
Write a statement that removes the value at index 2 from the existing list bound to the variable name fashionable_outfits.
fashionable_outfits.pop(2)
The best structure for implementing a multi-way decision in Python is a) if-else (b) try (c) if (d) if-elif-else
if-elif-else
In a mixed-type expression involving ints and floats, Python will convert: (a) both ints and floats to strings (b) ints to floats (c) ints to strings (d) floats to ints
ints to floats
Define a function below, output_lines, which takes a single string filename as an argument. Complete the function to open the file for reading, read the lines of the file, and print out each line.
def output_lines(filename): lines = open(filename, 'r') for data in lines: print(data) lines.close()
Write a statement that takes a variable named f that contains a file object and reads its contents into a Python list of lines. Store the resulting list into a variable named lines.
lines= f.readlines()
Write a statement that reverses the contents of the list locations in place. That is, what was the first element should become the last element (and vice-versa) through the whole list.
locations.reverse()
Write a statement that opens a file named 'readme.txt' for writing and assigns the resulting file object to a variable named my_file.
my_file = open('readme.txt', "w")
Write a statement that takes a variable named file_obj that contains a file object and reads the next 26 characters into a variable named my_str.
my_str = file_obj.read()[:26]
Write a statement that creates a single string from an existing list of strings called state_names by inserting the string ', ' between every pair of strings in the list. The resulting string should be put into a variable called output_str.
output_str =', '.join(state_names)
The function below takes two arguments, a string name with a person's first name and a string called favorite_colors which has peoples' first names followed by their favorite color. Complete the function to return name's favorite color. For example, given "Morgan" and "Skyler Purple Morgan Green Logan Blue Jackie Red Parker Blue", your function should return "Green". Hint - you may want to split the string and then use the resulting list to solve this question!
def return_fav_color(name, favorite_colors): splits = favorite_colors.split() result = None for i in range(len(splits)): if name==splits[i]: result = splits[i+1] return result
The function below takes one parameter: a list of numbers (num_list). Complete the function to return a new list containing only the negative numbers from the original list. For this question, you'll first want to create an empty list. Then, you'll want to visit every element of the original list checking to see if it is negative. For the negative elements, you'll append them to your new list. Finally, return the new list.
def select_negative_numbers(num_list): listq = [] for i in num_list: if i < 0: listq.append(i) return listq
Write a statement that inserts the value 'call mom' into the list priorities so that it becomes the element at index 7.
priorities.insert(7, 'call mom')
Define a function called sorted_word_list, which takes a sentence (a string) as a parameter. Complete the function to make and return a list of the words in the sentence in sorted order. Hint - you will likely want to use split method.
def sorted_word_list(string1): sort = string1.split() sort.sort() return sort
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 15 because that is the number you get when you add 1 + 2 + 3 + 4 + 5. Hint: We recommend using the range function and a for loop.
def sum_up_to_n(name): if name>=0 and type(name)== int: Sum=0 for i in range(0,name+1): Sum +=i 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): result = [] for i in data: if type(i) == int or type(i) == float: if i % multiple == 0: result.append(i) return result
The function below takes one parameter: a string (full_name) consisting of words separated by whitespace. Make an acronym from the words by making a new word by selecting the first letter of each word, and then capitalizing the new word. For example, if given the string 'international business machines', your function would return 'IBM'. To implement this, split the given string to get a list of strings (one string per word). Iterate through the words, building a string from the first letters of each word. Then convert the result to upper case letters using the upper() function.
def make_acronym(full_name): words = full_name.split() result = '' for word in words: result += word[0].upper() return result
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(',')))) def main(): print(maximum_from_CSV(input())) if __name__ == "__main__": main()
Write a statement that sorts in reverse order (from largest to smallest) the list stores in place.
stores.sort(reverse=True)