CSC 111: Python
If a Python source file named my_file.py is imported by other Python code, what is the value of __name__ if it is accessed inside the imported file? Select one: - 'main' - None of these choices. - '__main__' - 'my_file.py' - 'my_file'
'my_file'
Deep Copy: - Duplicates _____ - Copies _____ - Elements of the copied collection are _____
- Duplicates everything - Copies the entire reference object - Elements of the copied collection are not shared
cmp(dict1, dict2) returns ___ when dict1 < dict2
-1
Sallow Copy: - Duplicates _____ - Copies _____ - Elements of the copied collection are _____
-Duplicates as little as possible - Copies only the "shallow" value, i.e., the reference - Elements of the copied collection are shared
cmp(dict1, dict2) returns ___ when dict1 > dict2
1
Consider the following 2 calls to the numpy.polyfit function: a,b = np.polyfit(xs, ys, 1) a, b, c, d, e = np.polyfit(xs, ys, 4) Match the correct description of the arguments to the numpy.polyfit function with their position in the parameter list of the function. The first parameter: ____ The Second Parameter:____ The Third Parameter: ____
1. An array-like ordered collection of x values 2. An array-like ordered collection of y values 3. An integer value for the degree of the fitted polynomial.
Identify and place in order the 4 steps in the Basic Plotting Algorithm. Step 1: _____ Step 2: _____ Step 3: _____ Step 4: _____
1. Gather values to plot 2. Determine type of plot 3. Call appropriate plot function 4. Show the plot
Given the following NumPy arrays: import numpy as np arr1 = np.array([2, 14, 5, 1, 8]) arr2 = np.array([2, 2, 2, 2, 2]) arr3 = np.array([5, 4, 3, 2, 1]) Match each of the following arithmetic expressions with the result of evaluating the expression. sum(arr2)
10
Given a user input of 7, what is the output of the following Python code? t = 0 v = int(raw_input('Enter a number: ')) for n in range(v): t += n print t
21
Consider the following Python code: state = 'North Carolina' sl = len(state) choice = int(raw_input('Enter a number between 0 and ' + str(sl - 1) + ': ')) if 0 <= choice < sl: print state[choice] else: print 'Invalid entry!' For each of the user inputs below, select the correct output from this code: 4: _____ 14: _____ 12: _____ 0: _____
4: h 14: Invalid entry! 12: n 0: N
What is the maximum number of return statements Python allows in a function definition? Select one: - Any number - 0 - 2 - 127 - 1
Any number
The characteristics that distinguish one class of object from another and also help to distinguish between objects of the same type.
Attributes
The things an object can do, either in an interaction with other objects or to modify its internal state.
Behaviors
True or False: In Python, all of the elements of a list must be the same type.
False
True or False: In a Python dictionary, the order of items is always the order that the key-value pairs are added to the dictionary.
False
True or False: Like a list, the elements of a tuple can be modified.
False
True or False: There is a single universal standard for the CSV file format used to import and export data to and from spreadsheets and databases.
False
True or False: Numpy array elements cannot be accessed using an index in the same way they are used for lists and tuples.
False
True or false: A single try: statement can have only one except: statement.
False
This characteristic is used to distinguish one object from another in a program, even if those objects represent the same "type" or "class" of objects.
Identity
Which of the following characteristics should be true of a good test case? (You may choose more than one). Select one or more: - It anticipates new requirements beyond the customer spec. - It provides a clear way to determine if the test passed or failed. - It shows exactly how to set up the test. - It is written as quickly as possible. - It tests the integration of disparate components. You can port it across systems easily.
It shows exactly how to set up the test. It provides a clear way to determine if the test passed or failed.
Consider the following code: d = {'Name': 'Dana', 'Age': 12, 'Grade': 6, 'Name': 'Kelly'} print d['Name'] What is the output generated by the print statement?
Kelly
What type of error will be raised if you try to access a key that is not in the dictionary?
KeyError
Given the following code, select the correct output: temp_str = "Second argument: {1}, first one: {0}" arg1 = 47 arg2 = 11 out_str = temp_str.format(arg1, arg2) print out_str Select one: - None of these are the correct output. - Second argument: 11, first one: 47 - 11 47 - Second argument: 47, first one: 11 - 47 11
Second argument: 11, first one: 47
Consider the following Python code: a, b, c, d = 1, 2, 3 What values are stored in the variables a, b, c, and d after his code executes? Select one: - b has the value 2 - d has the value 3 - c has the value 3 - a has the value 1 - This code generates an error and no values are assigned.
This code generates an error and no values are assigned. ValueError: need more than 3 values to unpack
True or False: In Python, an exception indicates that something unusual has occurred during a program's execution that may cause the program to be in an unstable state.
True
True or False: When you are finished reading from or writing to a file, your program should close the file.
True
True or False: A numpy array can be created from a list as long as the values are all of the same type.
True
True or False: In a Python dictionary, a key is used to access a value stored in the dictionary.
True
Given the following NumPy arrays: import numpy as np arr1 = np.array([2, 14, 5, 1, 8]) arr2 = np.array([2, 2, 2, 2, 2]) arr3 = np.array([5, 4, 3, 2, 1]) Match each of the following arithmetic expressions with the result of evaluating the expression. arr2 / (arr1 * 1.0)
[ 1. , 0.14285714, 0.4, 2. , 0.25]
Consider the Python code below and answer the following 3 questions def fun(lst1, lst2, str1): if len(lst1) > 3: lst1 = lst1[:3] lst2[0] = 'ahoy' str1 = ''.join(lst2) arg1_lst = ['a','b','c','d'] arg2_lst = ['hello', 'mother', 'and', 'father'] arg_str = 'sister' fun(arg1_lst, arg2_lst, arg_str) print arg1_lst # Print 1 print arg2_lst # Print 2 print arg_str # Print 3 What is the output generated by the print statement at the line marked Print 1?
['a', 'b', 'c', 'd']
Consider the Python code below and answer the following 3 questions def fun(lst1, lst2, str1): if len(lst1) > 3: lst1 = lst1[:3] lst2[0] = 'ahoy' str1 = ''.join(lst2) arg1_lst = ['a','b','c','d'] arg2_lst = ['hello', 'mother', 'and', 'father'] arg_str = 'sister' fun(arg1_lst, arg2_lst, arg_str) print arg1_lst # Print 1 print arg2_lst # Print 2 print arg_str # Print 3 What is the output generated by the print statement at the line marked Print 2?
['ahoy', 'mother', 'and', 'father']
Which of the following is not a valid list definition in Python? Select one: - [10, 20, 30, 40] - ['spam', 2.0, 5, [10, 20] - ['crunchy frog', 'ram bladder', 'lark vomit'] - ['Cheddar', 'Edam', 'Gouda'] - []
['spam', 2.0, 5, [10, 20]
Given the following NumPy arrays: import numpy as np arr1 = np.array([2, 14, 5, 1, 8]) arr2 = np.array([2, 2, 2, 2, 2]) arr3 = np.array([5, 4, 3, 2, 1]) Match each of the following arithmetic expressions with the result of evaluating the expression. arr2 - arr3: ______
[-3, -2, -1, 0, 1]
Consider the following function definition: def fun(t, e, i): ret = t[:i] ret.append(e) return ret + t[i:] What is the output from the following code? lst = [1,2,3,4,5] print fun(lst, 'spam', 2)
[1, 2, 'spam', 3, 4, 5]
Given the following NumPy arrays: import numpy as np arr1 = np.array([2, 14, 5, 1, 8]) arr2 = np.array([2, 2, 2, 2, 2]) arr3 = np.array([5, 4, 3, 2, 1]) Match each of the following arithmetic expressions with the result of evaluating the expression. arr1 * arr3
[10, 56, 15, 2, 8]
Given the following NumPy arrays: import numpy as np arr1 = np.array([2, 14, 5, 1, 8]) arr2 = np.array([2, 2, 2, 2, 2]) arr3 = np.array([5, 4, 3, 2, 1]) Match each of the following arithmetic expressions with the result of evaluating the expression. arr3**3
[125, 64, 27, 8, 1]
Given the following NumPy arrays: import numpy as np arr1 = np.array([2, 14, 5, 1, 8]) arr2 = np.array([2, 2, 2, 2, 2]) arr3 = np.array([5, 4, 3, 2, 1]) Match each of the following arithmetic expressions with the result of evaluating the expression. arr1 + arr2
[4, 16, 7, 3, 10]
Consider the following function definition: def fun(t, e, i): ret = t[:i] ret.append(e) return ret + t[i:] What is the output from the following code? lst = [8, 7, 3, 15, -4] print fun(lst, 'foo', 3) Select one: - [8, 7, 3, 15, -4] - [2, 4, 'spam', 6, 8, 10] - [2, 'foo', 4, 6, 8, 10] - [8, 7, 3, 'foo', 15, -4] - [8, 7, 3]
[8, 7, 3, 'foo', 15, -4]
A second variable referring to an object is an _____
alias
NumPy arrays are similar to Python lists except... Select one: - elements cannot be accessed with an index. - array elements must be numeric values. - NumPy arrays are immutable. - elements in an array are not ordered. - all of the elements must be the same type.
all of the elements must be the same type.
definition: adds a new element to the end of a list
append
dictionaries: returns value or default of none if key not in dictionary
d.get(key, default=none)
dictionary command: True if d has the key
d.has_key(key)
Consider a function words_in_text( text ) that takes a string of text as an argument and returns a dictionary containing an entry for every word in the input string. The text string contains lines of words separated by whitespace and no punctuation. The dictionary returned will contain an entry for every word (ignoring capitalization) with an associated value of the number of times the word showed up in the file. Example Usage: >>> atext = "The quick brown fox jumps over the lazy dog\n" >>> atext += "The fast red fox jumps around the sleeping dog\n" >>> atext += "The excited dog barks at the lazy brown fox\n" >>> atext += "The fast brown fox jumps over the sleeping dog\n" >>> print words_in_text( atext ) {'brown': 3, 'lazy': 2, 'around': 1, 'excited': 1, 'barks': 1, 'over': 2, 'fox': 4, 'dog': 4, 'fast': 2, 'sleeping': 2, 'at': 1, 'quick': 1, 'the': 8, 'jumps': 3, 'red': 1} Select all of the following functions that are correct implementations of these requirements? Select one or more: def words_in_text(text): text = text.lower() hist = dict() tx = text.split() for w in tx: if w in hist: hist[w] += 1 else: hist[w] = 1 return hist def words_in_text(text): text = text.lower() hist = dict() tx = text.split() for w in tx: hist[w] = 1 + hist.get(w, 1) return hist def words_in_text(text): text = text.lower() hist = dict() tx = text.split() for w in tx: hist[w] = 1 + hist.get(w, 0) return hist def words_in_text(text): text = text.lower() hist = [] tx = text.split() for w in tx: if w in hist: hist[w] += 1 else: hist[w] = 1 return hist def words_in_text(text): hist = dict() tx = text.split() for w in tx: if w in hist: hist[w] += 1 else: hist[w] = 1 return hist
def words_in_text(text): text = text.lower() hist = dict() tx = text.split() for w in tx: hist[w] = 1 + hist.get(w, 0) return hist def words_in_text(text): text = text.lower() hist = dict() tx = text.split() for w in tx: if w in hist: hist[w] += 1 else: hist[w] = 1 return hist
command: To remove more than one element
del
command: If you know index and don't need the element any more
del [i]
Match the definition with the appropriate dictionary method. Remove all items from the dictionary.
dict.clear()
create a new dictionary using the keys in d
dict.fromkeys(d)
Match the definition with the appropriate dictionary method. Return the value associated with key.
dict.get(key)
Match the definition with the appropriate dictionary method. Get a list of the keys in a dictionary.
dict.keys()
Match the definition with the appropriate dictionary method. Update the dictionary with the key/value pairs from the dictionary, "other", overwriting any existing keys.
dict.update([other])
Match the definition with the appropriate dictionary method. Get a list of all of the values stored in a dictionary object.
dict.values()
{ } is an empty ____
dictionary
definition: takes a list and adds all elements
extend
Which of the following is the proper way in Python to open a file named "words.txt" and to make it available for reading? Select one: - open('words.txt') - fin = open('words.txt', 'w') - fin = open(words.txt) - fin = open('words.txt', 'a') - fin = open('words.txt')
fin = open('words.txt')
Which of the following is the correct way in Python to open a file named "output.txt" so that you can write to it? Select one: - fout = open(output.txt, w) - fout = open('output.txt', 'r') - fout = open('output.txt', 'w') - open('output.txt', 'w') - fout = close('output.txt', 'w')
fout = open('output.txt', 'w')
Keys are ____ - mutable -immutable
immutable
tuples are ______ lists
immutable
The commonly accepted way to import the numpy module is Select one: - from numpy import np - None of these choices - import numpy as np - import numpy - import np as numpy
import numpy as np
[ ] is an empty ____
list
The formula for computing the standard deviation of a set of values is: standard deviation formula Select the expression that correctly computes the standard deviation for a NumPy array of values (xs in this case). You should assume that all of the appropriate import statements have been included. Select one: - math.sqrt(sum(xs - xs.mean())**2/(len(xs) - 1)) - math.sqrt(sum((xs - xs.mean())**2)) - math.sqrt((xs - xs.mean())**2)/(len(xs) - 1) - math.sqrt(sum((xs - xs.mean())**2)/len(xs) - 1) - math.sqrt(sum((xs - xs.mean())**2)/(len(xs) - 1))
math.sqrt(sum((xs - xs.mean())**2)/(len(xs) - 1))
Identify the name(s) that are legal function names in Python. Select all that apply. Select one or more: - myFunction - my-function - func3 - my_function - 3rd_function
myFunction func3 my_function
When used to read the contents of a structured text file, the loadtxt function in the numpy module returns a(n) Select one: - list of strings - array of strings - numpy.ndarray - list of dictionaries - all of these choices, depending upon the file organization
numpy.ndarray
commands: If you know index and need to use the deleted element
pop(i)
opening a file: 'r' = 'w' = 'a' =
r = read w = write a = append
Choose the selection that best completes this sentence: When the csv.reader function is called with a file object, the reader returns an object that allows you to... Select one: - write the file out as an Excel spreadsheet document. - automatically create a dictionary from the entire file - None of these choices is correct. - read all of the lines from the file at once - read one line at a time from the file
read one line at a time from the file
Variable associated with an object holds a ______ to that object
reference
command: remove If you know the element value but not the index
remove(elt)
Consider the Python code below and answer the following 3 questions def fun(lst1, lst2, str1): if len(lst1) > 3: lst1 = lst1[:3] lst2[0] = 'ahoy' str1 = ''.join(lst2) arg1_lst = ['a','b','c','d'] arg2_lst = ['hello', 'mother', 'and', 'father'] arg_str = 'sister' fun(arg1_lst, arg2_lst, arg_str) print arg1_lst # Print 1 print arg2_lst # Print 2 print arg_str # Print 3 What is the output generated by the print statement at the line marked Print 3?
sister
definition: arranges elements from low to high
sort
Select all of the correct ways to create a dictionary object in Python. Select one or more: sp2ger = ['uno': 'ein', 'dos': 'zwei', 'tres': 'drei'] sp2ger = {'uno'='ein', 'dos'='zwei', 'tres'='drei'} sp2ger = {'uno': 'ein', 'dos': 'zwei', 'tres': 'drei'} sp2ger = {} sp2ger = () sp2ger = dict()
sp2ger = {'uno': 'ein', 'dos': 'zwei', 'tres': 'drei'} sp2ger = {} sp2ger = dict()
text vs. binary files
text: stores information as plain text binary: everything else, i.e., images, sound files
Given: number_str = raw_input('Input a floating-point number: ') invalid = True while invalid: # Line 1 print 'The number is ', number_float We want code that will continue to prompt the user for input until a correctly formatted floating-point value is entered so it can be printed at the bottom. Which of the following is the correct replacement for the comment at Line 1?
try: number_float = float(number_str) invalid = False except ValueError: number_str = raw_input('Try again: Input a floating-point number: ')
( ) is an empty ____
tuple
Given the following information about the code that has already been executed, select the Python code snippet that correctly writes the data to a csv file. The variable columns refers to a tuple of strings representing column names in the output file. The variable d_lst refers to a list of dictionaries containing the data to be written to the output file. The number of values stored in each dictionary in d_lst is the same as the number of column names in columns. Select one: with open('my_data.csv', 'wb') as fout: csv_write = csv.writer(fout) writer = csv.DictWriter(fout, columns) for d in d_lst: writer.writerow(d) with open('my_data.csv', 'r') as fout: csv_write = csv.writer(fout) csv_write.writerow(columns) writer = csv.DictWriter(fout, columns) for d in d_lst: writer.writerow(d) with open('my_data.csv', 'wb') as fout: csv_write = csv.writer(fout) csv_write.writerow(columns) writer = csv.DictWriter(fout, columns) for d in d_lst: writer.writerow(d) None of these choices is correct with open('my_data.csv') as fout: csv_write = csv.writer(fout) csv_write.writerow(columns) writer = csv.DictWriter(fout, columns) for d in d_lst: writer.writerow(d)
with open('my_data.csv', 'wb') as fout: csv_write = csv.writer(fout) csv_write.writerow(columns) writer = csv.DictWriter(fout, columns) for d in d_lst: writer.writerow(d)
Select the correct boolean expression for each condition in the function m(x). This function should return "Small" if the value stored in x is divisible by both 3 and 5, "multiple of 5" if divisible only by 5, "multiple of 3" if divisible only by 3, and "Orange" otherwise. if ______________: return 'Small'
x % 3 == 0 and x % 5 == 0
Select the correct boolean expression for each condition in the function m(x). This function should return "Small" if the value stored in x is divisible by both 3 and 5, "multiple of 5" if divisible only by 5, "multiple of 3" if divisible only by 3, and "Orange" otherwise. elif _____________: return 'multiple of 5'
x % 5 == 0
Which of the following are acceptable variable names in Python? Select one or more: - rich&Bill - xyzzy - long_variable_name - good2Go - 2ndVar
xyzzy long_variable_name good2Go
Consider the following Python code: x = "spam" y = 45.201 x, y = y, x Select the choices that indicate the correct values stored in the variables x and y. Select one or more: - y has the value 'spam' - y has the value 45.201 - x has the value 'spam' - x has the value 45.201 - This code causes an error.
y has the value 'spam' x has the value 45.201
What is the string formatting placehoder, used in a template string, that will insert the second argument to the format function into the template right justified in a 20 character wide space? Select one: - {1:4.5f<20} - {2:<20} - {1:15.5f} - {1:>20} - {1:<20}
{1:>20}