CS 105 - Final Review

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Create a string literal for the following lines of text. You will need to know how to escape the backslash character. (feel free to cut and paste into your answer). Make sure there are no spaces immediately adjacent to your quotes. alligator\koala \ kangaroo

"alligator\\koala \\ kangaroo"

What is the value of variable x after the following piece of code executes? x = 'Mangosteen' y = 'Tamarind' x = y y = x

'Tamarind'

If the variable x begins with the value 12, what is the value of x after the following piece of code executes? if x >= 20: x *= 2 else: x += 7

19

What is the value of rval after the function call? def list_func(li, x): for i in range(len(li)): if li[i] < x: return i return -1 rval = list_func([19, 18, 15, 11, 10, 9, 8, 7], 16)

2

What is the output of the code below? dict1 = {'Mulberry': 3, 'Longan': 8, 'Gooseberry': 0} dict2 = {'Georgia': 2, 'Alabama': 9, 'New Jersey': 5} if dict1["Mulberry"] == dict2["Alabama"]: print(dict2["Alabama"]) else: print(dict1["Mulberry"])

3

What is the value of rval after the function call? def list_func(li, x): for y,z in enumerate(li): if x == z: return y return -1 rval = list_func([11, 18, 4, 3], 3)

3

What is the result of float(int(3.5))?

3.0 The result of int(3.5) is 3 and the result of float(3) is 3.0

If the variable x begins with the value 6, what is the value of x after the following piece of code executes? if x <= 1: x += 6 if x != 6: x *= 2

6

If the variable animal_str contains the string 'hound', does this boolean expression evaluate to True or False? animal_str != 'hound'

False

A function's scope is the number of lines of code in that function.

False A function's scope is the collection of variables and their values that are available while that function is executing.

Python is a compiled language.

False Python is an interpreted language. This makes Python slower for some tasks, but makes Python very flexible in how it can be used (e.g., one can use it interactively).

Python lists can hold only objects of type int, float, and string.

False Python lists can hold any type of objects, including other list objects.

In Python, the any() function returns the first (in list order) Truthy value from a list given as an argument.

False The any()function takes a list and returns True if any elements in the list are Truthy. Otherwise, it returns False.

Does the boolean expression below evaluate to True or False? 'z6\nb R'.islower()

False islower() returns True if there are no upper case characters and there is at least one lowercase character. The character 'R' is a kind of uppercase letter. Also, recall that '\n' is a newline and '\t' is a tab, both of which are whitespace characters.

What does an assignment statement do?

It causes the computer to store the result of the statement's expression in memory so you can use the result in a later Python statement. Assignment statements consist of the name of a variable to be updated, followed by an equals sign, followed by an expression to compute the new value to be assigned to that variable.

Write a short, high-level English language description of the code in the highlighted region. Do not give a line-by-line description. Assume that the variable x is a list of strings. You can assume that the code compiles and runs without error. def f(x): for val in x: if len(val) > 0: print(val)

Possible Answers: 1) Print all of the non-empty strings in the given list 2) Print every string from the list x that isn't the empty string 3) Output all of the strings that have at least one character

Write a short, high-level English language description of the code in the highlighted region. Do not give a line-by-line description. Assume that the variable x is a list of numbers (either ints or floats). You can assume that the code compiles and runs without error. def f(x): if len(x) == 0: return None y = x[0] for val in x: if val > y: y = val print(y)

Possible Answers: 1) Print the largest number in a given list 2) find the biggest number from list x and print it 3) print the maximum value of the provided list

Write a short, high-level English language description of the code in the highlighted region. Do not give a line-by-line description. Assume that the variable x is a list. You can assume that the code compiles and runs without error. def f(x): for val in x: if x.count(val) > 1: return True return False

Possible Answers: 1) Return True if there are any duplicates in the given list. Otherwise, return False. 2) Return False if every element in the provided list is unique. Otherwise, return True. 3) returns a Boolean indicating whether there are duplicates in a list

Write a short, high-level English language description of the code in the highlighted region. Do not give a line-by-line description. Assume that the variables x and y are both lists. You can assume that the code compiles and runs without error. def f(x, y): if len(x) > len(y): return x return y

Possible Answers: 1) Return the longer of a pair of lists; return the second list if they are both the same length 2) Given two lists, return the one that is longer. If equal in length, return y. 3) of two given lists, return the longer one. Return y if they are the same length.

Write a short, high-level English language description of the code in the highlighted region. Do not give a line-by-line description. Assume that the variable x is a list of numbers (either ints or floats) and the variable y is a number. You can assume that the code compiles and runs without error. def f(x, y): for i in range(len(x)): x[i] -= y

Possible Answers: 1) Subtract a number from every element in a list 2) Reduce each element of list x by y 3) lower the value of all list entries by a given number

In the following Python statement, is the variable x being read, written, or both? y = x - 10

Read

If the variable num_list contains the list [688, 441, 844, 441], does this boolean expression evaluate to True or False? num_list[1] != 688

True

In general, nested for loops are required for iterating through nested lists.

True Commonly, there will be one for loop for each dimension of the data (e.g., a list of lists of lists would require a triply-nested for loop).

When slicing a sequence, it is legal to leave out either or both the starting or ending index (i.e., [:7], [3:], and [:]).

True If the beginning index is left out, the slice starts at the beginning of the original sequence. If the ending index is left out, the slice ends at the end of the original sequence.

If both are integers, x > y is the same as (x >= y) and (x != y).

True If x is greater than or equal to y and x is not equal to y, then x must be greater than y.

In HTML, image elements don't need a closing </img> tag.

True Image elements don't contain any content, so they are void elements that don't need a closing tag. The URL for an image is specified using asrcattribute in the opening (only) tag.

In Python, function objects are immutable.

True Once a function has been created, the function object can't be modified. That said, you can change bindings between names and objects, so the name used in a function definition can later be re-bound to a different function (or even a different type of data).

Information can be passed into a function through parameters.

True Parameters are used to provide values to functions. Functions may also change the values of mutable parameters.

Variables defined in a function are local to that function.

True The variables defined in a function can only be used inside that function.

The literals for type bool are:

True, False

Write a list with 4 elements that could be passed to this function to get it to return the integer 1. def f(x): return x.index(-31)

[0, -31, 2, 3]

Create a Coord class from scratch. Objects of your class should have two instance attributes called 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): return Coord(self.x_coord * other.x_coord, self.y_coord * other.y_coord)

Below is a working start to a Student class that provides a constructor. Extend the class so that when a Student object is passed to the print function, that it prints Hello. My name is followed by a single space and the contents of the name attribute followed by a period. For example, if the Student's name was Inigo Montoya, printing the Student object would print: Hello. My name is Inigo Montoya. The intended way for you to do this is to override the builtin __str__ method of objects.

class Student: def __init__(self, name): self.name = name def __str__(self): return "Hello. My name is " + self.name + "."

Create a class that can be used to create new TikTok accounts. This class will have the following attributes: username: A string representing the username of the new account. bio: A string representing the bio of a new account. following: A list of strings containing the usernames of all the accounts you follow (initially empty). In addition to the __init__ method, this class has two other methods: follow and unfollow each of which take a user name and adds and removes that username from the following list, respectively.

class TikTok: def __init__(self, username, bio): self.username, self.bio, self.following = username, bio, [] def follow(self, follower_username): self.following.append(follower_username) def unfollow(self, follower_username): self.following.remove(follower_username)

Create a class that stores a (1) student's name, (2) their associated list of letter grades, and (3) a conversion table between letter grade and points (grade_to_gpa). Also, create a method called report_gpa that returns their total GPA based the list of grades stored in the object. NOTE: you need to put the __init__ method first and the report_gpa method second.

class Transcript: def __init__(self, name, grades): self.name = name self.grades = grades self.grade_to_gpa = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F': 0.0} def report_gpa(self): total_credits = 0 for grade in self.grades: total_credits += grade_to_gpa[grade] return to

Write a statement that takes a variable named file_object that contains a file object and reads its contents into a Python list of lines. Store the resulting list into a variable named contents.

contents = file_object.readlines()

Write a statement that adds the int 19 to the end of an existing list called customer_counts.

customer_counts.append(19)

The function below takes two parameters: a list num_list and an int stop. Complete the function so that it appends every third number in the range from 0 up to, but not including, stop to the list num_list. You should start from 0: for example, given stop = 7, your function should append 0, 3, and 6 to the list. 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(num_list, stop): # Implement your function here. Be sure to indent your code block! for i in range(0, stop, 3): num_list.append(i)

The function below takes one parameter: (exam_score) containing an integer from 0 to 100. Complete the function to return a single capital letter ('A', 'B', 'C', 'D', or 'F'). The letter you return is a function of the parameter as indicated by the table below. A = 90-100 B = 80-89 C = 70-79 D = 60-69 F = 0-59

def assign_grade(exam_score): # Implement your function here. Be sure to indent your code block! if exam_score <= 59: return "F" elif exam_score <= 69: return "D" elif exam_score <= 79: return "C" elif exam_score <= 89: return "B" elif exam_score <= 100: return "A"

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(lst_num): if not lst_num: return 0 else: return sum(lst_num) / len(lst_num)

The function below takes a single string parameter called sentence. Your function should return True if the sentence contains at least one copy of each of the following vowels: a, e, i, o, and u. Otherwise, return False. The vowels can be either upper case or lower case.

def contains_all_values(sentence): vowels = set(['a', 'e', 'i', 'o', 'u']) sentence = sentence.lower() return all(v in sentence for v in vowels)

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 = ['a', 'e', 'i', 'o', 'u'] count = 0 for c in s: if c in vowels: count += 1 return 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 substr as 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 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): if not str_list: return '<ol></ol>' else: result = '<ol>' for item in str_list: result += '<li>' + item + '</li>' result += '</ol>' return result

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(nums, x): return [n - x for n in nums]

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 filter_strs_with_even_vowel_count(str_li): vowels = 'aeiou' even_vowel_count = lambda s: sum(1 for c in s if c in vowels) % 2 == 0 return list(filter(even_vowel_count, str_li))

Given a file path to a CSV file containing both positive and negative integers write a program that reads the file, finds the largest integer in the file, and returns that value. The largest integer in the file is no larger than 9999 and the smallest is no smaller than -9999.For example given a path to a CSV with the following data the function should return 10: 1,2,3,4\n -1,-2,-3,-4\n 1,2,3,10

def find_largest_csv_val(filename): largest_num = -10000 f = open(filename, 'r') for line in f: nums = line.strip().split(',') for num in nums: num =int(num) if num > largest_num: largest_num = num return largest_num

The function below, find_largest_value_key, takes a single argument: a dictionary data_dict. The dictionary can have any data type as a key, but all of the dictionaries values are of type string. Complete the function below to return the key which corresponds to the longest value in the dictionary. For example, given the dictionary {"sample": "Four", 5: "A longer string"}, the function should return 5

def find_largest_value_key(data_dict): largest_key = None largest_value_length = 0 for key, value in data_dict.items(): if len(value) > largest_value_length: largest_value_length = len(value) largest_key = key return largest_key

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): even_str = "" for val in string_inputs: if len(val) % 2 == 0: even_str = val return even_str

Define a function below, get_subset, which takes two arguments: a dictionary of strings (keys) to integers (values) and a list of strings. All of the strings in the list are keys to the dictionary. Complete the function such that it returns the subset of the dictionary defined by the keys in the list of strings. For example, with the dictionary {"puffin": 5, "corgi": 2, "three": 3} and the list ["three", "corgi"], your function should return {"corgi": 2, "three": 3}. Since dictionaries are unordered, you can add the keys to the new dictionary in any order.

def get_subset(dct, keys): return {k: dct[k] for k in keys}

The function below takes a single string parameter: given. Complete the function to return an integer equal to the number of words in the given sentence. Hint: We recommend using the split function to break the sentence into words.

def how_many_words(given): words = given.split() return len(words)

Given a list of integers (int_lst) and a list of strings (str_lst), the largest_index function should find the index of the largest item in the list of integers and return the item at that index in the list of strings.

def largest_index(int_lst, str_lst): max1 = max(int_lst) index = int_lst.index(max1) return str_lst[index]

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 line_number = 0 for i, data in enumerate(numbers): if int(data) > largest_num: largest_num = int(data) line_number = i + 1 return f'{largest_num} {line_number}'

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): with open(filename, "r") as f: numbers = f.readlines() smallest_num = 101 for data in numbers: if int(data) < smallest_num: smallest_num = int(data) return smallest_num

The function below takes a single parameter, a list of numbers called number_list. Complete the function to return a string of the provided numbers as a series of comma separate values (CSV). For example, if the function was provided the argument [22, 33, 44], the function should return '22,33,44'. Hint: in order to use the join function you need to first convert the numbers into strings, which you can do by looping over the number list to create a new list (via append) of strings of each number.

def number_list_to_csv(number_list): # Convert the numbers to strings string_list = [str(num) for num in number_list] # Join the strings using commas as separators return ",".join(string_list) (0/9 --> Don't know)

The function below takes one parameter: an integer (begin). Complete the function so that it prints the numbers starting at begin down to 1, each on a separate line. There are two recommended approaches for this: (1) use a for loop over a range statement with a negative step value, or (2) use a while loop, printing and decrementing the value each time.

def print_countdown(begin): # Implement your function here. Be sure to indent your code block! while begin >= 1: print(begin) begin -= 1

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): 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. For example, given "Jaime Abraham <[email protected]> (333) 333-3331 105 Made Up Drive", your function should return "[email protected]". Hint - you'll want to consider how you can locate the email address and then how to isolate it from the rest.

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

Given a list of lists where each sublist contains string, find and return the list that contains the greatest total number of characters. Note: your answer should use all blocks.

def sublist_with_most_chars(lists): greatest_list = [] for sublist in lists: char_count = len('' ''.join(sublist)) if char_count > len('' ''.join(greatest_list)): greatest_list = sublist return greatest_list

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. The recommended approach for this: (1) create a variable to hold the current sum and initialize it to zero, (2) use a for loop to process each element of the list, (3) test each element to see if it is an integer or a float, and, if so, add its value to the current sum, (4) return the sum at the end.

def sum_lengths(info): # Implement your function here. Be sure to indent your code block! current_sum = 0 for value in info: if isinstance(value, (int,float)): current_sum += value return current_sum

The function below takes one parameter: a string called uid_string that contains a series of user IDs in Comma Separated Values (CSV) format. Complete the function to return a CSV of their illinois email addresses instead. For example, given "sample5, test3", your function should return "[email protected], [email protected]". To complete this question you'll need to split the CSV into a list, edit the elements, and join them back together.

def turn_uids_to_emails(uid_string): uids = uid_string.split(", ") emails = [uid + "@illinois.edu" for uid in uids] return ", ".join(emails)

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. For example, ["sparrow, "SpArRoW", "hawk", "dove", "DOVE"] should return ["sparrow", "hawk", "dove"].

def unique_bird_log(exciting_birds): unique_birds = set([bird.lower() for bird in exciting_birds]) return list(unique_birds)

Write a statement that removes the key-value pair with the key 23 from the existing dictionary called directed_edges.

del directed_edges[23]

Write a statement that takes a variable named text_file that contains a file object and reads its contents into a Python list of lines. Store the resulting list into a variable named file_lines.

file_lines = text_file.readlines()

Lists in HTML documents can be ordered or unordered, with elements of lists being identified with the <li>. Write a python function, extract_a_list, which takes a single argument: a string holding all the text from an HTML page with a list in it. Have the function return a python list of all the entries in the HTML list. If there is no HTML list, an empty python list should be returned. An example HTML file for testing can be found here: lists.html. Using this example, your code should return ["Alpaca","Cats"].

import re def extract_a_list(html_string): li_pattern = re.compile(r'<li>(.*?)</li>', re.DOTALL) matches = li_pattern.findall(html_string) return [match.strip() for match in matches] if matches else []

What is a value for input that could be passed to the function below such that it outputs 3? input = ? def magic_number(input): value = 0 if 'r' in input: value += 1 if 'l' in input: value += 2 else: value += 4 else: value += 8 if 's' in input: value += 16 else: value += 32 return value print(magic_number(input))

input = "real"

Enter a string that will cause 4 lines to be printed to the screen. li = letters = 'aeiou' for y in li: if y not in letters: continue print(y)

li = "aeio"

Enter a string that will cause 5 lines to be printed to the screen. li = letters = 'aeiou' for y in li: if y not in letters: continue print(y)

li = 'aeiou'

Write a statement that creates a new list called locations_sorted that is a sorted version of the list locations, without changing the list locations.

locations_sorted = sorted(locations)

A function can modify the value of a parameter only if it's

mutable Mutable parameters can be changed and the changes seen by the caller. For immutable parameter, assignment will only bind a new value to the parameter name and not change the value of the argument in the caller.

Write a statement that counts the number of times that the value 22 is in an existing list called daily_calls_made and puts the result in a variable called num_matches.

num_matches = daily_calls_made.count(22)

Write a statement that takes a variable named ofile that contains a writeable file object and writes into it the contents of the variable text_string.

ofile.write(text_string)

Before reading or writing to a file, a file object must be created via

open f=open(fname, 'r')is required before reading or writing to a file.

Write a statement that creates an object (with default values) from the class FoodItem and assign it to a variable named ordered.

ordered = FoodItem()

Write a range expression that will produce the following sequence of values: [1, 3, 5]

range(1, 6, 2)

Input a list of strings for s such that the code prints 5 after the code executes. s = def f(s, v): x = 0 for l in s: if v in l: x += 1 print(x) f(s, 'z')

s = ['z', 'z', 'z', 'z', 'z']

A loop pattern that continues until a special value is input is called a(n)

sentinel loop A sentinel is a term used in programming to indicate a specific value meant to serve as a boundary in an input. For example, a negative number might be used to mark the end of a sequence of positive numbers.

Write a statement that creates a new list called stores_sorted that is a sorted version of the list stores, without changing the list stores.

stores_sorted = sorted(stores)

Input a letter for string v such that the code prints 0 after the code executes. v = def f(s, v): x = 0 for l in s: if v in l: x += 1 print(x) f(['hedgehog', 'termite', 'antelope'], v)

v = "v"

Input a Dictionary for the variable x such that the output of the code below is: {'New York': 5, 'Florida': 10, 'Virginia': 2} x = dict1 = x dict2 = {'New York': 5, 'Florida': 7, 'Virginia': 2} dict2["Florida"] = dict2["Florida"] + dict1["Banana"] print(dict2)

x = {'Banana': 3}

Input a value for the variable y such that the variable x is 2 after the code executes. y = ? x = y +3 * 3

y = -7


Kaugnay na mga set ng pag-aaral

Geography: Chapter 13- Weathering,Karst Landscapes, and Mass Movements

View Set

Quantitative Methods Exam Ch 1-3

View Set

Technology for Success - Module 10 Quiz

View Set

React/Redux/Webpack/React Native

View Set

Chromatography Practical Questions

View Set

Chapter 51: Care of Patients with Musculoskeletal Trauma

View Set