CS 105 UIUC Final Study

Ace your homework & exams now with Quizwiz!

Ariel has a baby that is having trouble sleeping. In this problem, we'll get a list with True values for when the baby is awake and False for when the baby is sleeping. Create a function called when_baby_sleeps that takes a single argument of type list of boolean values. Your function should return the first index where the baby is asleep. You can assume that the list always has at least one true value and one false value.

def when_baby_sleeps(lst): for i in range(len(lst)) if lst[i] == False: return i

Write a function called which_vowels_present that takes a single string parameter. Complete the function to return a list of strings indicating which vowels (a, e, i, o, and u) are present in the provided string. The case of the vowels in the original string doesn't matter, but they should be lowercase when returned as part of the list. The order of the vowels in the list doesn't matter.

def which_vowels_present(string): vowels = ['a', 'e', 'i', 'o', 'u'] string = string.lower() new_list = [] for i in vowels: if i in string: new_list.append(i) return new_list

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

del rankings[31]

prints everything on the same line

end = ' '

A partially absolute reference for the cell J4, so that the column won't change but the row would change normally

$J4

fruits = ['apple', 'banana', 'cherry'] x = fruits.index("cherry")

2

HTML file structure

<!DOCTYPE html> <html lang = "en"> <meta charset ="UTF-8"> <title>Page title</title> <body> document body </body> </html>

=MATCH

=MATCH(what you are looking up, where, and how exact (0))

=COUNTIFS

Count the number of cells in a range that fit multiple criteria

=COUNTIF(range, criteria)

Counts the number of cells within a range that meet the given criteria

An operating system is a hardware component that executes the instructions of a computer program.

False

Functions can be used before they are defined as long as you invoke them from inside of the file in which they are defined.

False

In Python, a function can return only one value.

False

In Python, class attributes are read only.

False

Python uses list comprehensions to interpret list literals.

False

String 'slicing' is used to split a string into multiple pieces.

False

There is usually only one correct solution to a problem involving decision structures.

False

Does this evaluate to True or False? not True or False

False -the not operator has higher precedence than and and or operators.

A partially absolute reference for the cell J4, so that the column will change normally, but the row won't

J$4

def f(x, y) for i in range(len(x)): x[i] -=y

Subtract a number from every element in a list

enumerate()

The enumerate() function is a built-in function that returns an enumerate object. This lets you get the index of an element while iterating over a list.

The file.read() method returns the file contents as a string.

True

x = ('apple', 'banana', 'cherry') y = enumerate(x)

[(0, 'apple'), (1, 'banana'), (2, 'cherry')]

Which of the following is not a Python type-conversion function:

abs

Write a statement that removes the string 'porcupine' from an existing list called animals_to_feature. You can assume that the item is present and that it exists in the list only once.

animals_to_feature.remove('porcupine') -use remove to remove the first matching value

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

cheeses_sorted = sorted(cheeses) -sorted creates a new list

Assuming that the variable letter contains a string with a single letter of the alphabet, write an expression using the ord() and chr() functions to return the next letter of the alphabet.

chr(ord(letter) + 1) chr = number into letter ord = letter into number

Code reading problem: def f(x): if x < 0: return -x return x

computes the absolute value of a number.

=COUNT

counts the non-empty cells in a row or column =COUNTBLANK will count the empty cells

=COUNTA

counts the numbers of cells in a range that are not blank (count is only fo numbers, counta counts anything as long as it's not empty)

The function below, average_from_file, takes one argument: the name of a file full of numbers. Complete the function so that it opens the file and returns the average of the numbers in the file.

def average_from_file(num_file): f = open(num_file) sum = 0 count = 0 for num in f: sum += int(num) count +=1 return sum/count

Define a function below called average_numbers. 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 average_numbers(num_list): if len(num_list) ==0: return 0 else: return sum(num_list) / len(num_list)

The function below 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.

def bold_word(paragraph, word): if word in paragraph: new_word = "<b>" + word +"</b>" paragraph = paragraph.replace(word, new_word) return paragraph

The following function takes a list of numbers and is supposed to return the sum of only the positive numbers. Please fix the function.

def calc_sum(nums): total = 0 for num in nums: if num > 0: total += num return total

The function below takes a string arguments, input_string. Complete the function so that it returns True if input_string is a palindrome. Otherwise, return False.

def check_palindrome(input_string): if input_string == input_string[::-1]: return True else: return False

In the function below, return True if value is strictly between lower and upper. (By strictly between we mean that it can't be either of the end points.) Otherwise, return False. Assume all the arguments are numbers (i.e., floats or integers).

def check_value_in_range(value, lower, upper): return value > lower and value < upper

The function below takes two string arguments. Complete the function to return True if the strings are anagrams and False otherwise. Anagrams are words that contain all the same letters in the same amount.

def check_whether_anagram(word1, word2): if sorted(word1) == sorted(word2): return True else: return False

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

def convert_to_csv(number_list): return ",".join(str(i) for i in number_list)

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(a_list): dic = {} for i in a_list: if i in dic: dic[i] += 1 else: dic[i] = 1 return dic

The function below takes one parameter: a list of integers (num_list). Complete the function to count how many of the numbers in the list are even.

def count_even_integers(num_list): even_count = 0 for num in num_list: if num % 2 == 0: even_count += 1 return even_count

The function below takes one argument: a list of data. Complete the function so that it writes each element of the list as a string to a file output_file.txt, one per line.

def dump_contents(data): my_file = open('output_file.txt','w') for thing in data: my_file.write(str(thing)+'\n') my_file.close

The function below takes a single string parameter: sentence. Complete the function to return everything but the middle 10 characters of the string. You can assume that the parameter always has at least twelve characters and is always an even number of characters long.

def exclude_middle_chars(sentence): middle = len(sentence) // 2 result = sentence[0: middle -5] + sentence [middle + 5:] return result

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.

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

The title for HTML documents are put inside of a pair of <title> and </title> tags. Write a function called extract_title that takes a single parameter, a string containing HTML. Your function should return a string containing the title from the web page; that is, return the string after the <title> tag and before the </title> tag.

def extract_title(html): start_index = html.find(<title>) +7 end_index = html.find(</title>) return html[start_index:end_index]

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. Complete the function to return a string containing one of the words in sentence that contains letter (in either upper case or lower case). Your code should return the word with its capitalization in the original sentence. If there are multiple words in sentence that contain letter, you can return any of them.

def extract_word(sentence, letter): words = sentence.split() for i in words: if letter in i.lower() return i

The function below takes a list of strings as an argument, string_inputs. The function is supposed to find the first string in the list with an even length and then return that string - can you fix it? If no even length string is found, return an empty string "".

def find_first_even_str(string_inputs): for val in string_inputs: if len(val) % 2 == 0: return val return ""

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): if len(string_list) == 0: return "" else: return max(string_list, key = len)

The function below should search the list my_list for the value target and return the index. Can you fix it?

def find_targ_in_list(my_list, target): result = my_list.index(target) return result

The function below takes a single string parameter: email_address. 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.

def get_netid(email_address): get_netid = email_address[:-13] return get_netid

The function below takes two parameters: an integer index and a string parameter CSV_string. This string parameter will hold a comma-separated collection of integers: '111,22,3333,4'. Complete the function to return the indexth value (counting from zero) from the comma-separated values as an integer.

def get_nth_int_from_CSV(index,CSV_string): csv_data = CSV_string.split(',') nth_index = csv_data[index] return int(nth_index)

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): nsl = [] for values in shopping_cart: nsl.append(price_lookup.get(values)) return nsl

The function below, get_value_if_key, takes two arguments: the dictionary data_dict and a key of any type my_key. Fix the code to return the value from data_dict for key my_key if that key exists. The function should not return anything otherwise (i.e. return None).

def get_value_if_key(data_dict, my_key): if my_key in data_dict: return data_dict[my_key] return None

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

def get_words_with_a(words): sentence = words.split() result = [] for word in sentence: if 'a' in word: result.append(word) return result

Formal and actual parameters are matched up by

position

Write a statement that removes the value at index 1 from the existing list bound to the variable name fashionable_outfits.

fashionable_outfits.pop(1) -use pop when you're removing at a certain index

def f(x): for val in x: print(val)

print every element of a list on their own line

Accessing a single character out of a string is called:

indexing

Write a statement that takes a variable named open_file 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 = open_file.readlines()

Define a function below, print_countdown, which takes a single integer argument (i.e. begin). Complete the function so that it prints the numbers starting at begin down to 1, each on a separate line.

def print_countdown(begin): for num in range(begin, 0, -1): print(num) -it starts at begin, and since it wants the countdown to go to one, you have to make the range go to zero.

The function below takes one parameter: a dictionary (dictionary). Complete the function so that it prints out each of the given dictionary's keys, on the same line with a space after each key. Recall that dictionaries store key:value pairs and that when you iterate through a dictionary with a for loop, you are iterating through the keys.

def print_dict_keys(dictionary) for key in dictionary.keys(): print(key , end = "")

Print the keys of dictionary, one per line

def print_dict_keys(dictionary): for key in dictionary: print(key)

The function below takes one parameter: a dictionary (dictionary). Complete the function so that it prints out each value stored in the dictionary, each on a separate line. Recall that dictionaries store key:value pairs. Also, when you iterate through a dictionary with a for loop, you are interating through the keys

def print_dict_values(dictionary): for i in dictionary.values(): print(i)

The function takes a single string parameter, which is the name of a file. Complete the function to open the file for reading, read the lines of the file, and print out each line.

def print_lines_of_file(filename): my_file = open(filename) lines = my_file.readlines() for line in lines: print(line)

The function below takes one parameter: a list of strings (string_list). Complete the function so that it prints out each string on a separate line.

def print_list_elements(string_list): for i in string_list: print(i)

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): for sub_list in list: print(*sub_list)

Write a statement that opens a file named 'README.txt' for reading and assigns the resulting file object to a variable named my_file.

my_file = open('README.txt', 'r')

Valid variable names

names that begin with an underscore, or letter, followed by any combination of letters, numbers, and underscores.

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

ofile.write(publisher)

Write a statement that takes a variable named output_file that contains a writeable file object and writes into it the string 'mule'.

output_file.write('mule')

The function below takes two integer parameters: low and high. Complete the function so that it prints the numbers from low to high in order, including both low and high, each on a separate line.

def print_range(low, high): for num in range(low, high +1) print(num) -if you just do range(low, high), it won't include high, so you have to add one more to high.

Print the dictionary value associated with a given key

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

The function below takes a single string input, containing a web site user's first name. This function should return a personalized HTML span containing a greeting and the user's first name as provided in the following form: (assuming that 'Julia' was the given first name.) <span>Hello, Julia</span>

def return_greeting_span(first_name): return "<span> Hello, " + first_name + "</span>"

The function below, return_subdictionary, takes a single argument: a dictionary number_dict. The dictionary has strings as keys and integer values. The function should create and return a new dictionary which contains only the key:value pairs from the original dictionary which have even numbers as values. Returning an empty dictionary is fine. Can you fix it?

def return_subdictionary(number_dict): new_dict = {} for key,value in number_dict.items(): if value % 2 == 0: new_dict[key] = value return new_dict

Write a statement that inserts the value 'do laundry' into the list priorities so that it becomes the element at index 8.

priorities.insert(8, 'do laundry')

Write a statement that adds the int 4 to the end of an existing list called product_sales.

product_sales.append(4)

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(string_list): str = [] for x in string_list: if len(x) == 0: return str else: str.append(x)

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 (value_list) of various types.

def sum_lengths(value_list) sum = 0 for num in value_list: if (type(num) == int) or (type(num) ==float): sum+= num return sum

The function below takes a single parameter: a list of numbers called the_numbers. Return a new list containing just the three largest numbers (in any order). Your function shouldn't modify the original list. You can assume that the list always contains at least 3 numbers.

def three_largest_numbers(the_numbers): copy_list = the_numbers copy_list = sorted(copy_list, reverse = True) #to get it in largest to smallest new_list = [ ] new_list.append(copy_list[0]) new_list.append(copy_list[1]) new_list.append(copy_list[2]) return new_list

Define a function below called increase_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 increased by the second argument.

def increase_elements_by_x(num, x): new_list = [ ] for i in num: new_list.append(i + x) return new_list

In the function below, return True if the input string parameter consists of a single lowercase letter; otherwise, return False.

def is_a_single_letter(string_arg): for letters in string_arg: if len(string_arg) ==1: if (str(letters)) > = 'a' and str(letters) <= 'z': return True return False

The function list_combination takes two lists as arguments, list_one and list_two. Return from the function the combination of both lists - that is, a single list such that it alternately takes elements from both lists starting from list_one. You can assume that both list_one and list_two will be of equal lengths.

def list_combination(list_one, list_two) new_list = [ ] for i in range(len(list_one)): new_list.append(list_one[i]) new_list.append(list_two[i]) return new_list

Write a Python function called list_extender which takes three arguments - three lists. It should extend the first list with the second two lists, but not change the second two lists and not return anything.

def list_extender(list1, list2, list3): list1.extend(list2) list1.extend(list3)

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

def make_acronym(full_name): new_list = full_name.split() result = "" for i in new_list: result += i[0].upper() return result

The function below takes a single input, containing list of strings. This function should return string containing an HTML unordered list with each of in_list strings as a list item. For example, if provided the list ['CS 105', 'CS 125', 'IS 206'], your function should return a string containing the following. The only whitespace that is important is those contained in the given strings (e.g., the space between CS and 105).

def make_html_unordered(in_list): result = '<ul>\n' for i in in_list: result += '<li>' + i + '</li>\n' return result + '</ul>'

Write a range expression that will produce the following sequence of values: [-5, -2, 1, 4, 7]

range(-5, 8, 3) -whatever you are decrementing or incrementing by goes at the end.

Write a statement that sorts in reverse order (from largest to smallest) the list responses in place.

responses.sort(reverse =True)

Write a statement that creates a single string from an existing list of strings called states by inserting the string ',' between every pair of strings in the list. The resulting string should be put into a variable called result_string.

result_string = ','.join(states) -read the question carefully. It's asking you to use join, not split.

def f(x, y): return x[y:]

returns a copy of the list without the first y elements

def f(x, y): return x[:y]

returns a new list containing the elements before the index y in the given list

symmetric_difference()

returns a set that contains all items from both sets, but not the items that are present in both sets.

union()

returns a set that contains all items from the original set and all the items from the specified set (if something is present in both sets it'll only appear once)

index()

returns the position at the first occurrence of the specified value

isupper()

returns true if there are no lowercase characters and there is at least one uppercase character.

isdigit()

returns true is all the characters are the numbers 0-9

isalnum()

returns true is all the characters in the string are lowercase or uppercase letters, or the number 0-9 (no punctuation or special characters)

Write a statement that slices 6 characters of the string name starting 3 characters from the beginning. Put this value into a variable named selection.

selection = [3:9]

Write a statement that slices the last 8 characters of the string variable book_title and puts its result into a variable named selection.

selection = book_title[-8:]

Write a statement that slices the first 9 characters of the string variable name and puts its result into a variable named selection.

selection = name[:9]

Write a statement that slices 11 characters of the string sentence ending 3 characters from the end. Put this value into a variable named selection.

selection = sentence[-14:-3]

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

sentinel loop

Write a statement that updates the value associated with the key 'Akee' to the value 9 in the existing dictionary called stock.

stock['Akee'] = 9

Write a statement that reverses the contents of the list stores in place. That is, what was the first element should become the last element (and vice-versa) through the whole list.

stores.reverse()

Write a statement that takes a variable named file_obj that contains a file object and reads the next 27 characters into a variable named text_string.

text_string = file_obj.read()[:27]

x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.union(y) print(z)

{'microsoft', 'cherry', 'google', 'apple', 'banana'}

x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.symmetric_difference(y) print(z)

{'microsoft', 'cherry', 'google', 'banana'}


Related study sets

Plant Test Review Questions and Answers

View Set

Psychology 110 - Chapter 1 - Exam 1

View Set

LearningCurve - Chapter 5: Price Controls and Quotas: Meddling with Markets

View Set

Limited Partnerships and Limited Liability Companies

View Set

abbreviations for levels of assistance

View Set