Final Exam MIS
Which of the following statements is false? 1. DataFrames have a describe method that calculates basic descriptive statistics for the data and returns themas a two-dimensional array. 2. In a DataFrame, the statistics are calculated by column. 3. Method describe nicely demonstrates the power of array-oriented programming with a functional-style call—Pandas handles internally all the details of calculating these statistics for each column. 4. You can control the precision of floating-point values and other default settings with pandas' set_optionfunction.
1. DataFrames have a describe method that calculates basic descriptive statistics for the data and returns themas a two-dimensional array.
Which of the following statements is false? 1. A try clause may be followed by one or more except clauses that immediately follow the try clause's suite. 2. The except clauses also are known as exception handlers. 3. Each except clause specifies the type of exception it handles. 4. After the last except clause, an optional else clause specifies code that should execute only if the code in the try suite raised an exception.
4. After the last except clause, an optional else clause specifies code that should execute only if the code in the try suite raised an exception.
Which of the following statements about code snippets that use Account is false? 1. The following code uses a constructor expression to create an Account object and initialize it with an account holder's name (a string) and balance (a Decimal): account1 = Account('John Green', Decimal('50.00')) 2. The following expressions access an Account object's name and balance attributes: account1.name account1.balance 3. The following snippets deposit an amount into an Account and access the new balance: account1.deposit(Decimal('25.53')) account1.balance 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. Classes are new function types. 2. Most applications you'll build for your own usewill commonly use either no custom classes or just a few. 3. You can contribute your custom classes to the Python open-source community, but you are not obligated to do so. Organizations often have policies and procedures related to open-sourcing code. 4. All of the above statements are true.
1. Classes are new function types.
The json module enables you to convert objects to JSON (JavaScript Object Notation) text format. This is known as________ the data. 1. chunking 2. calibrating 3. serializing 4. registering
3. serializing
A read-only property has ________. 1. only a setter 2. only a getter 3. a setter and a getter 4. neither a setter nor a getter
2. only a getter
Which of the following statements is false? 1. The array methods reshape and resize both enable you to change an array's dimensions. 2. Method reshape returns a deep copy of the original array with the new dimensions. It does not modify the original array. 3. Method resize modifies the original array's shape. 4. All of the above statements are true.
2. Method reshape returns a deep copy of the original array with the new dimensions. It does not modify the original array.
Which of the following statements is false? Assume the following array definitions: import numpy as np integers = np.array([[1, 2, 3], [4, 5, 6]]) floats = np.array([0.0, 0.1, 0.2, 0.3, 0.4]) 1. The array function determines an array's element type from its argument's elements. 2. You can check the element type with an array's dtype attribute. 3. For performance reasons, NumPy is written in the Java programming language and uses Java's data types. 4. All of the above statements are true.
3. For performance reasons, NumPy is written in the Java programming language and uses Java's data types.
A pandas _________ is an enhanced two-dimensional array. 1. Series 2. DataFrame 3. dictionary 4. array
2. DataFrame
Which of the following would be accepted by a program strictly looking for four integers of data in CSV format? 1. 100, 85 77,9 2. 100,85,,77,9 3. '100,85,77,9' 4. 100,85, 77,9
4. 100,85, 77,9
Which of the following statements is true with respect to displaying an array of 1000 items or more? 1. NumPy always drops the middle rows and middle columns from the output. 2. NumPy always drops only the middle rows from the output. 3. NumPy always drops only the middle columns from the output. 4. NumPy drops the middlerows, middle columns or both from the output.
4. NumPy drops the middlerows, middle columns or both from the output.
Which of the following statements is false? 1. Series provides many methods for common tasks including producing various descriptive statistics, like count, mean, min, max, etc. 2. Each of the descriptive statistics in Part (a) is a functional-style reduction. 3. Calling Series method describe produces all the Part(a) descriptive stats and more. 4. The 25%, 50% and 75% statistics produced by Series method describe are quartiles: 50% represents the median of the sorted values, 25% represents the median of every second one of the sorted values and 75% represents the median of every fourth one of the sorted values
4. The 25%, 50% and 75% statistics produced by Series method describe are quartiles: 50% represents the median of the sorted values, 25% represents the median of every second one of the sorted values and 75% represents the median of every fourth one of the sorted values
When you evaluate a variable in IPython it calls the corresponding object's _________ special method to produce a string representation of the object. 1. __init__ 2. __str__ 3. __string__ 4. __repr__
4. __repr__
If the contents of a file should not be modified, open the file for________—another example of the principle of least privilege. This prevents the program from accidentally modifying the file. 1. writing only 2. reading only 3. reading and writing 4. none of the above
2. reading only
Which of the following statements is false? 1. For big data applications, you'll also want to choose algorithms that are easy to sequentialize—that will enable you to put lots of processors to work simultaneously. 2. The simplest and most apparent algorithms often perform poorly—developing more sophisticated algorithms can lead to superior performance. 3. Big O notation concisely classifies algorithms by how hard they have to work to get the job done—it helps you compare the efficiency of algorithms. 4. All of the above statements are true
1. For big data applications, you'll also want to choose algorithms that are easy to sequentialize—that will enable you to put lots of processors to work simultaneously.
Which of the following statements is false? 1. JSON objects are similar to Python lists. Each JSON object contains a comma-separated list of property names and values, in curly braces. For example, the following JSON object might represent a client record:{"account": 100, "name": "Jones", "balance": 24.98} 2. JSON also supports arrays which, like Python lists, are comma-separated values in square brackets. For example, the following is an acceptable JSON array of numbers:[100, 200, 300] 3. Values in JSON objects and arrays can be strings in double quotes, numbers, JSON Boolean values (true or false), null (to represent no value, like None in Python), arrays and other JSON objects. 4. All of the above statements are true
1. JSON objects are similar to Python lists. Each JSON object contains a comma-separated list of property names and values, in curly braces. For example, the following JSON object might represent a client record:{"account": 100, "name": "Jones", "balance": 24.98}
Which of the following statements is false? 1. Many applications acquire resources, such as files, network connections, database connections and more. You should release resources when your application terminates. 2. The with statement acquires a resource and assigns its corresponding object to a variable. 3. The with statement allows the application to use the resource via that variable. 4. The with statement calls the resource object's close method to release the resource when program control reaches the end of the with statement's suite
1. Many applications acquire resources, such as files, network connections, database connections and more. You should release resources when your application terminates.
Which of the following statements is false? 1. NumPy's array is optimized for heterogeneous numeric data that's accessed via integer indices. 2. Data science presents unique demands for which more customized data structures are required. 3. Big data applications must support mixed data types, customized indexing, missing data, data that's not structured consistently and data that needs to be manipulated into forms appropriate for the databases and data analysis packages you use. Pandas is the most popular library for dealing with such data. 4. Pandas provides two key collections—Series for one-dimensional collections and DataFrames for two-dimensional collections.
1. NumPy's array is optimized for heterogeneous numeric data that's accessed via integer indices.
Which of the following is false? 1. Python has separate string and character types. 2. You can use string method isdigit when validating user input that must contain only digits. 3. String method isalnum returns True if the string on which you call the method is alphanumeric—that is, it contains only digits and letters. 4. All of the above statements are true.
1. Python has separate string and character types.
Which of the following statements is false? 1. Seaborn function regplot's x and y keyword arguments are two-dimensional arrays of the same length representing the x-y coordinate pairs to plot. 2. Pandas automatically creates attributes for each column name if the name can be a valid Python identifier. 3. Seaborn and Matplotlib auto-scale the axes, based on the data's range of values. 4. All of the above statements are true
1. Seaborn function regplot's x and y keyword arguments are two-dimensional arrays of the same length representing the x-y coordinate pairs to plot.
Which of the following statements about the selection sort sorting in increasing order is false? 1. Selection sort is a simple, efficient, sorting algorithm. 2. Its first iteration selects the smallest element in the array and swaps it with the first element. The second iteration selects the second-smallest item (which is the smallest item of the remaining elements) and swaps it with the second element. 3. The algorithm continues until the last iteration selects the second-largest element and swaps it with the second-to-last index, leaving the largest element in the last index. 4. After the ith iteration, the smallest i items of the array will be sorted into increasing order in the first i elements of the array
1. Selection sort is a simple, efficient, sorting algorithm.
Which of the following statements is false? 1. The file open modes for writing and appending raise a FileNotFoundError if the file does not exist. 2. Each text-file mode has a corresponding binary-file mode specified with b, as in 'rb' or 'wb+'. 3. You use binary-file modes for reading or writing binary files, such as images, audio, video, compressed ZIP files and many other popular custom file formats. 4. All of the above statements are true.
1. The file open modes for writing and appending raise a FileNotFoundError if the file does not exist.
Which of the following statements is false? 1. The name pandas is derived from the term "panel data," which is data for spatial measurements, such as stock prices or historical temperature readings. 2. NumPy and pandas are intimately related. Series and DataFrames use arrays "under the hood." Series and DataFrames are valid arguments to many NumPy operations. Similarly, arrays are valid arguments to many Series and DataFrame operations. 3. Series and DataFrames make it easy for you to perform common tasks like selecting elements a variety of ways,filter/map/reduce operations (central to functional-style programming and big data), mathematical operations, visualization, data preparation and more. 4. All of the above statements are true
1. The name pandas is derived from the term "panel data," which is data for spatial measurements, such as stock prices or historical temperature readings.
Which of the following statements is false? 1. Searching data involves determining whether a value (referred to as the search key) is present in the data and, if so, finding its location. 2. Two popular search algorithms are the simple binary search and the faster but more complex linear search. 3. Sorting places data in ascending or descending order, based on one or more sort keys. 4. All of the above statements are true
2. Two popular search algorithms are the simple binary search and the faster but more complex linear search.
Which of the following statements is false? 1. The vast majority of object-oriented programming you'll do in Python is object-based programming in which you primarily use objects of new custom classes you create. 2. To take maximum advantage of Python you must familiarize yourself with lots of preexisting classes. 3. Over the years, the Python open-source community has crafted an enormous number of valuable classes and packaged them into class libraries, available on the Internet at sites like GitHub, BitBucket, SourceForge and more. This makes it easy for you to reuse existing classes rather than "reinventing the wheel." 4. Widely used open-source library classes are more likely to be thoroughly tested, bug free, performance tuned and portable across a wide range of devices, operating systems and Python versions
1. The vast majority of object-oriented programming you'll do in Python is object-based programming in which you primarily use objects of new custom classes you create.
Which of the following statements is false? 1. Variables, lists, tuples, dictionaries, sets, arrays, pandas Series and pandas DataFrames offer long-term data storage. 2. Computers store files on secondary storage devices, including solid-state drives, hard disks and more. 3. Some popular text file formats are plain text, JSON (JavaScript Object Notation) and CSV (comma-separated values). 4. All of the above statements are true
1. Variables, lists, tuples, dictionaries, sets, arrays, pandas Series and pandas DataFrames offer long-term data storage.
Which of the following statements about sorting unique items is false? 1. Sorting data (i.e., placing the data in a particular order—ascending or descending) is one of the most important types of computing applications. 2. An important item to understand about sorting unique values is that the end result—the sorted array—will be the same no matter which algorithm you use to sort the array. The choice of algorithm affects only the run time of the program. 3. Selection sort and insertion sort—are relatively simple to program but inefficient. Merge sort—is much faster than selection sort and insertion sort but harder to program. 4. All of the above statements are true
2. An important item to understand about sorting unique values is that the end result—the sorted array—will be the same no matter which algorithm you use to sort the array. The choice of algorithm affects only the run time of the program.
Which of the following statements is false? You'll generally manipulate arrays using concise functional-style programming techniques with internal iteration. 2. Because arrays are iterable, you cannot use external iteration with them. 3. You can iterate through a multidimensional array as if it were one-dimensional by using its flat attribute. 4. All of the above statements are true.
2. Because arrays are iterable, you cannot use external iteration with them.
Which of the following statements is false? 1. The amount of memory in a computer is finite, so only a certain amount of memory can be used to store activation records on the function-call stack. 2. If more recursive function calls occur than can have their activation records stored on the stack, a fatal error known as an infinite loop occurs. 3. Running out of memory for the function-call stack typically is the result of infinite recursion, which can be caused by omitting the base case or writing the recursion step incorrectly so that it does not converge on the base case. 4. All of the above statements are true.
2. If more recursive function calls occur than can have their activation records stored on the stack, a fatal error known as an infinite loop occurs.
Which of the following statements is false? 1. The simplest form of the raise statement is raise ExceptionClassName 2. In most cases, when you need to raise an exception, it's recommended that you customize the exception type with a meaningful exception name. 3. The raise statement creates an object of the specified exception class. Optionally, the exception class name maybe followed by parentheses containing arguments to initialize the exception object—typically to provide a custom error message string. 4. Code that raises an exception first should release any resources acquired before the exception occurred.
2. In most cases, when you need to raise an exception, it's recommended that you customize the exception type with a meaningful exception name.
Which of the following statements is false? Consider this text from Shakespeare's Romeo and Juliet: soliloquy = 'To be or not to be, that is the question' 1. String method index searches for a substring within a string and returns the first index at which the substring is found; otherwise, a ValueError occurs. The following code returns 3: soliloquy.index('be') 2. String method rindex performs the same operation as index, but searches from the end of the string and returns the last index at which the substring is found; otherwise, a Value-Error occurs. The following code returns 3: soliloquy.rindex('be') 3. String methods find and rfind perform the same tasks as index and rindex but, if the substring is not found, return -1 rather than causing a ValueError. 4. All of the above statements are true.
2. String method rindex performs the same operation as index, but searches from the end of the string and returns the last index at which the substring is found; otherwise, a Value-Error occurs. The following code returns 3: soliloquy.rindex('be')
Which of the following statements is false? 1. Method replace takes two substrings. It searches a string for the substring in its first argument and replaces each occurrence with the substring in its second argument. The method returns a new string containing the results. 2. The following code replaces tab characters with commas: values = '1\t2\t3\t4\t5' values.replace('\t', ', ') 3. Method replace can receive an optional third argument specifying the maximum number of replacements to perform. 4. All of the above statements are true
2. The following code replaces tab characters with commas: values = '1\t2\t3\t4\t5' values.replace('\t', ', ')
Which of the following statements is false? 1. The linear search algorithm runs in O(n) time. 2. The worst case in the linear search algorithm is that every element must be checked to determine whether the search item exists in the array. If the size of the array is doubled, the number of comparisons that the algorithm must perform is quadrupled. 3. Linear search can provide outstanding performance if the element matching the search key happens to be at or near the front of the array. 4. Linear search is easy to program, but it can be slow compared to other search algorithms. If a program needs to perform many searches on large arrays, it's better to implement a more efficient algorithm, such as the binary search.
2. The worst case in the linear search algorithm is that every element must be checked to determine whether the search item exists in the array. If the size of the array is doubled, the number of comparisons that the algorithm must perform is quadrupled.
Which of the following statements is false? 1. The regular expression metacharacter \ begins each of the predefined regular expression character classes, which each match a specific set of characters. 2. The following code ensures that a string contains five consecutive digits: re.fullmatch(r'\d{5}', '02215') 3. A character class is a regular expression escape sequence that matches one or more characters. 4. The following code returns None because '9876' contains only four consecutive digit characters. re.fullmatch(r'\d{5}', '9876')
3. A character class is a regular expression escape sequence that matches one or more characters.
Preparing data for analysis is called __________. 1. data wrangling 2. data munging 3. Both (a) and (b) 4. Neither (a) nor (b)
3. Both (a) and (b)
Which of the following statements is false? 1. Operating systems typically can prevent more than one program from manipulating a file at once. 2. When a program finishes processing a file, the program immediately should close it to release the resource. This enables other programs to use the file (if they're allowed to access it). 3. Closing a file creates a resource leak in which the file resource is not available to other programs. 4. All of the above statements are true.
3. Closing a file creates a resource leak in which the file resource is not available to other programs.
Which of the following statements is false? 1. When you call a recursive function to solve a problem, it's actually capable of solving only the base case(s). If you call the recursive function with a base case, it immediately returns a result. 2. The recursion step executes while the original function call is still active (i.e., it has not finished executing). 3. For the recursion to eventually terminate, each time the function calls itself with a simpler version of the original problem, the sequence of smaller and smaller problems must converge on a recursion step. 4. All of the above statements are true
3. For the recursion to eventually terminate, each time the function calls itself with a simpler version of the original problem, the sequence of smaller and smaller problems must converge on a recursion step.
Which of the following statements is false? 1. String method splitlines returns a list of strings representing the lines of text split at each newline character in the original string. 2. Python stores multi-line strings with embedded \n characters to represent the line breaks. 3. For the string lines = """This is line 1 This is line2 This is line3""" the statement lines.splitlines(True) keeps the newlines and returns: ['This is line 1', '\nThis is line2', '\nThis is line3'] 4. All of the above statements are true
3. For the string lines = """This is line 1 This is line2 This is line3""" the statement lines.splitlines(True) keeps the newlines and returns: ['This is line 1', '\nThis is line2', '\nThis is line3']
Which of the following statements is false? 1. The following f-string formats the float value 17.489 rounded to the hundredths position: f'{17.489:.2f}' 2. Python supports precision only for floating-point and Decimal values. 3. Formatting is type dependent—if you try to use .2f to format a string like 'hello', a NameError occurs. 4. The presentation type f in the format specifier .2f is required.
3. Formatting is type dependent—if you try to use .2f to format a string like 'hello', a NameError occurs.
Which of the following statements is false? 1. You can specify custom indices for a Series with the index keyword argument when creating the Series, as in import pandas as pd grades = pd.Series([87, 100, 94], index=['Wally', 'Eva', 'Sam']) 2. In Part(a), we used string indices, but you can use other immutable types, even including integers not beginning at 0 and non consecutive integers. 3. If you initialize a Series with a dictionary, its values become the Series' indices, and its keys become the Series' element values. 4. All of the above statements are true.
3. If you initialize a Series with a dictionary, its values become the Series' indices, and its keys become the Series' element values.
Which of the following statements is false? 1. String method split with no arguments tokenizes a string by breaking it into substrings at each whitespace character, then returns a list of tokens. 2. To tokenize a string at a custom delimiter (such as each comma-and-space pair), specify the delimiter string (such as, ', ') that split uses to tokenize the string, as in: letters = 'A, B, C, D' letters.split(', ') 3. If you provide an integer as split's second argument, it specifies the maximum number of splits. The last token is the remainder of the string after the maximum number of splits. Assuming the string in Part (b), the code letters.split(', ', 1) returns ['A', 'B', 'C, D'] 4. There is also an rsplit method that performs the same task as split but processes the maximum number of splits from the end of the string toward the beginning.
3. If you provide an integer as split's second argument, it specifies the maximum number of splits. The last token is the remainder of the string after the maximum number of splits. Assuming the string in Part (b), the code letters.split(', ', 1) returns ['A', 'B', 'C, D']
Which of the following statements is false? 1. Pandas displays a Series in two-column formatwith the indexes left aligned in the left column and the values right aligned in the right column. 2. After listing the Series elements, pandas shows the data type (dtype) of the underlying array's elements. 3. It is easier to display a list than a Series in a nice two-column format. 4. All of the above statements are true.
3. It is easier to display a list than a Series in a nice two-column format.
Which of the following statements is false? 1. Many calculation methods can be performed on specific array dimensions, known as the array's axes. These methods receive an axis keyword argument that specifies which dimension to use inthe calculation, giving you a quick way to perform calculations by row or column in a two-dimensional array. 2. Assume that you want to calculate the average grade on each exam, represented by the columns of grades. Specifying axis=0 performs the calculation on all the row values within each column. Similarly, specifying axis=1 performs the calculation on all the column values within each individual row. 3. NumPy does not display trailing 0s to the right of the decimal point. Also, it does not display all element values in the same field width. 4. For a two-dimensional array grades in which each row represents one student's grades on several exams, we can calculate each student's average grade with: grades.mean(axis=1)
3. NumPy does not display trailing 0s to the right of the decimal point. Also, it does not display all element values in the same field width.
Which of the following algorithm is arranged in order from least efficient to most efficient? 1. O(log n), O(n2), O(n log n), O(n) 2. O(n), O(n log n), O(n2), O(log n) 3. O(n2), O(n log n), O(n), O(log n) 4. O(n log n), O(log n), O(n), O(n2)
3. O(n2), O(n log n), O(n), O(log n)
Which of the following statements is false? 1. Recursive functions (or methods) call themselves, either directly or indirectly through other functions (or methods). 2. Recursion might help you solve problems more naturally when an iterative solution is not apparent. 3. Sorting unique values is a fascinating problem, because no matter what algorithms you use, the final result is the same. So you'll want to choose algorithms that perform "the best"—usually, the ones that run the fastest or use the most memory. 4. All of the above statements are true.
3. Sorting unique values is a fascinating problem, because no matter what algorithms you use, the final result is the same. So you'll want to choose algorithms that perform "the best"—usually, the ones that run the fastest or use the most memory.
Which of the following statements is false? 1. f-strings were added to Python in Python 3.6. 2. You'll often see the format method in the Python documentation and in the many Python books and articles written before f-strings were introduced. 3. The following code formats the float value 17.489 rounded to the hundredths position: '{:.3f}'.format(17.489) 4. All of the above statements are true.
3. The following code formats the float value 17.489 rounded to the hundredths position: '{:.3f}'.format(17.489)
Which of the following statements are false? 1. The built-in open function opens a file and associates it with a file object. 2. The mode argument specifies the file-open mode, indicating whether to open a file for reading from the file, for writing to the file or both. 3. The mode 'w' opens the file for writing. If the file already exists, opening it for writing causes any new data to be appended to the end of the file. 4. At the end of the with statement's suite, the with statement implicitly calls the file object's close method to close the file.
3. The mode 'w' opens the file for writing. If the file already exists, opening it for writing causes any new data to be appended to the end of the file.
Which of the following statements is false? 1. For a text file, the read method returns a string containing the number of characters specified by the method's integer argument. For a binary file, the method returns the specified number of bytes. If no argument is specified, the method returns the entire contents of the file. 2. The readline method returns one line of text as a string, including the newline character if there is one. 3. The readline method issues an EndOfFileError when it encounters the end of the file. 4. The writelines method receives a list of strings and writes its contents to a file
3. The readline method issues an EndOfFileError when it encounters the end of the file.
________ time series have one observation per time, such as the average of the January high temperatures in New York City for a particular year;________ time series have two or more observations per time, such as temperature, humidity and barometric pressure readings in a weather application. 1. Univariate, bivariate 2. Single, multivariate 3. Univariate, multivariate 4. Single, mixed
3. Univariate, multivariate
The int function raises a________ if you attempt to convert to an integer a string (like 'hello') that does not represent a number. 1. NameError 2. ConversionError 3. ValueError 4. None of the above
3. ValueError
Which of the following statements is false? 1. Attempting to divide by 0 results in a ZeroDivisionError. 2. When a program attempts to divide by zero, the interpreter is said to raise an exception of type ZeroDivisionError. 3. When an exception is raised in an interactive IPython session, it displays the exception's traceback, then terminates the IPython session. 4. If an exception occurs in a script, IPython terminates the script and displays the exception's traceback.
3. When an exception is raised in an interactive IPython session, it displays the exception's traceback, then terminates the IPython session.
Which of the following statements is false? 1. Before working with text data, you'll often use regular expressions to validate the data. 2. A U.S. Social Security number contains three digits, a hyphen, two digits, a hyphen and four digits, and adheres to other rules about the specific numbers that can be used in each group of digits. 3. You must create your own regular expressions to ensure that they'll meet your needs. 4. Many sites provide interfaces in which you can test regular expressions
3. You must create your own regular expressions to ensure that they'll meet your needs.
Most object-oriented programming languages enable you to encapsulate (or hide) an object's data from the data from the client code. Such data in these languages is said to be ________ data. 1. public 2. protected 3. private 4. None of the above
3. private
Objects that "see" the data in other objects, rather than having their own copies of the data are called ________ objects. 1. subordinate 2. scene 3. view 4. aspect
3. view
Which of the following statements is false? 1. The NumPy (Numerical Python) library is the preferred Python array implementation—it offers a high-performance, richly functional n-dimensional array type called ndarray, which you can refer to by its synonym, array. 2. Operations on arrays are up to two orders of magnitude faster than those on lists. 3. Many popular data science libraries such as Pandas, SciPy(Scientific Python) and Keras (for deep learning) are built on or depend on NumPy. 4. A strength of NumPy is "array-oriented programming," which uses functional-style programming with external iteration to make array manipulations concise and straight forward, eliminating the kinds of bugs that can occur with the interna literation of explicitly programmed loops.
4. A strength of NumPy is "array-oriented programming," which uses functional-style programming with external iteration to make array manipulations concise and straight forward, eliminating the kinds of bugs that can occur with the interna literation of explicitly programmed loops.
Which of the following statements is false? 1. When an exception occurs in a try suite, it terminates immediately. 2. When there are except handlers, program control transfers to the first one that matches the type of theraised exception. If there are no except handlers that match the raised exception, a process called stack unwinding occurs. 3. When an except clause successfully handles an exception, program execution resumes with the finally clause (if there is one), then with the next statement after the try statement. 4. After an exception is handled, program control returns to the raise point
4. After an exception is handled, program control returns to the raise point.
Which of the following statements about insertion sort sorting into ascending order is false? 1. Insertion sort is another simple, but inefficient, sorting algorithm. 2. The first iteration of this algorithm takes the second element in the array and, if it's less than the first element, swaps it with the first element. The second iteration looks at the third element and inserts it into the correct position with respect to the first two, so all three elements are in order. 3. Using this algorithm, at the ith iteration, the first i elements of the original array are sorted, but they may not be in their final locations—smaller values may be located later in the array. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements are false? 1. A file object's readlines method reads an entire text file and returns each line as a string in a list of strings. 2. Calling readlines for a large file can be a time-consuming operation, which must complete before you can begin using the list of strings. 3. Using the file object in a for statement enables your program to process each text line as it's read. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. Each property defines a getter method which gets (that is, returns) a data attribute's value and can optionally define a setter method which sets a data attribute's value. 2. The @property decorator precedes a property's getter method, which receives only a self parameter. 3. Behind the scenes, a decorator adds code to the decorated function to enable the function to work with data attribute syntax. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. It may seem that providing properties with both setters and getters has no benefit over accessing the data attributes directly, but there are subtle differences. 2. A getter seems to allow clients to read the data at will, but the getter can control the formatting of the data. 3. A setter can scrutinize attempts to modify the value of a data attribute to prevent the data from being set to an invalid value. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. String methods lower and upper can convert strings to all lowercase or all uppercase letters, respectively. 2. Method capitalize copies the original string and returns a new string with only the first letter capitalized (sometimes called sentence capitalization). 3. Method title copies the original string and returns a new string with only the first character of each word capitalized (sometimes called book-title capitalization). 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. The array method copy returns a new array object with a deep copy of the original array object's data. 2. Assuming numbers is an array of integers, the following statement creates a deep copy of that array: import numpy as np numbers = np.arange(1, 6) numbers2 = numbers.copy() 3. After the statement in Part (b) executes, numbers2 has a separate copy of the data in numbers. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. Time series are sequences of values called observations associated with points in time. 2. Some examples of time series are daily closing stock prices, hourly temperature readings, the changing positions of a plane in flight, annual crop yields, quarterly company profits, and the stream of time-stamped tweets coming from Twitter users worldwide. 3. You can use simple linear regression to make predictions from time series data. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. You'll use lots of classes created by other people. 2. You can create your own custom classes. 3. Core technologies of object-oriented programming are classes, objects, inheritance and polymorphism. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. Calculating the mean of an array totals all of its elements regardless of its shape, then divides by the total number of elements. 2. You can perform array calculations on each array dimension as well. For example, in a two-dimensional array, you can calculate each row's mean or each column's mean. 3. The array methods sum, min, max, mean, std(standard deviation) and var (variance) are each functional-style programming reductions. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements is false? 1. With DataFrames you can specify custom indexes with the index keyword argument when we create a DataFrame, as in: grades_dict = {'Wally': [87, 96, 70], 'Eva': [100, 87, 90],'Sam': [94, 77, 90], 'Katie': [100, 81, 82],'Bob': [83, 65, 85]} import pandas as pd pd.DataFrame(grades_dict, index=['Test1', 'Test2', 'Test3']) 2. The following code uses the index attribute to change the DataFrame's indexes from sequential integers to labels: grades.index = ['Test1', 'Test2', 'Test3'] 3. When specifying the indexes, you must provide a one-dimensional collection that has the same number of elements as there are rows in the DataFrame; otherwise, a ValueError occurs. 4. All of the above statements are true
4. All of the above statements are true
Which of the statements is false? 1. Most resources that require explicit release, such as files, network connections and database connections, have potential exceptions associated with processing those resources. 2. A program that processes a file might raise IOErrors. For this reason, robust file-processing code normally appears in a try suite containing a with statement to guarantee that the resource gets released. 3. When a with statement is in a try suite, you can catch in except handlers any exceptions that occur and you do not need a finally clause because the with statement handles resource deallocation. 4. All of the above statements are true
4. All of the above statements are true
Which of the following statements about Numpy's linspance function is false? 1. You can produce evenly spaced floating-point ranges with linspace. 2. The function's first two arguments specify the starting and ending values in the range, and the ending value is included in the array. 3. The optional keyword argument num specifies the number of evenly spaced values to produce—this argument's default value is 50. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. A class can also support setting its attribute values individually via its properties. Assuming hour is a property of wake_up's class, the following statement changes an hour property value to 6: wake_up.hour = 6 2. Though the statement snippet in Part (a) appears to simply assign a value to a data attribute, it's actually a call to an hour method that takes 6 as an argument. 3. The hour method mentioned in Part (b) can validate the value, then assign it to a corresponding data attribute (which we might name _hour, for example). 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. By default, a Series has integer indexes numbered sequentially from 0. 2. The following code creates a Series of student grades from a list of integers: import pandas as pd grades = pd.Series([87, 100, 94]) 3. The Series argument in Part (b)'s code also maybe a tuple, a dictionary, an array, another Series or a single value. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. DataFrames can have custom row and column indices, and offer additional operations and capabilities that make them more convenient for many data-science oriented tasks. 2. DataFrames support missing data. 3. The Series representing each column may contain different element types. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. String method count returns the number of times its argument occurs in the string on which the method is called. 2. If you specify as the second argument to method count astart_index, as in sentence.count('to', 12) count searches only the slice string[start_index:]—that is, from start_index through end of the string. 3. If you specify as the second and third arguments of method count the start_index and end_index, as in sentence.count('that', 12, 25) count searches only the slice string[start_index:end_index]—that is, from start_indexup to, but not including, end_index. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The factorial of a positive integer n is written n! and pronounced "n factorial." 2. n! is the product n · (n - 1) · (n - 2) · ... · 1 with 1! equal to 1 and 0! defined to be 1. 3. 4! is the product 4 · 3 · 2 · 1, which is equal to 24. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The following code writes an object in JSON format to a file: import json with open('accounts.json', 'w') as accounts:json.dump(accounts_dict, accounts) 2. The snippet in Part (a) opens the file accounts.json and uses the json module's dump function to serialize the dictionary accounts_dict into the file. 3. JSON delimits strings with double-quote characters. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The linear search algorithm searches each element in an array sequentially. 2. If the search key does not match an element in the array, the algorithm informs the user that the search key is not present. 3. If the search key is in the array, the algorithm tests each element until it finds one that matches the search key and returns the index of that element. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The re module's search function looks in a string for the first occurrence of a substring that matches a regular expression and returns a match object (of type SRE_Match) that contains the matching substring. The match object's group method returns that substring, as in the following session: In [1]: import re In [2]: result = re.search('Python', 'Python is fun') In [3]: result.group() if result else 'not found' Out[3]: 'Python' 2. Function search returns None if the string does not contain the pattern. 3. You can search for a match only at the beginning of a string with function match. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. When you pass an object to built-in function repr—which happens implicitly when you evaluate a variable in an IPython session—the corresponding class's __repr__ special method is called to get the "official" string representation of the object. 2. Typically the string returned by __repr__ looks like a constructor expression that creates and initializes the object, such as: Time(hour=6, minute=30, second=0) 3. Python has a built-in function eval that could receive the string shown in Part (b) as an argument and use it to create and initialize a Time object containing values specified in the string. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. When you read a sentence, your brain breaks it into individual words, or tokens, each of which conveys meaning. 2. Interpreters like IPython tokenize statements, breaking them into individual components such as keywords, identifiers, operators and other elements of a programming language. 3. Tokens typically are separated by whitespace characters such as blanks, tabs and newlines, though other characters may be used—the separators are known as delimiters. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. You can force the sign on a positive number to display, as in: f'[{27:+10d}]' 2. The + before the field width in Part (a) specifies that a positive number should be preceded by a +.A negative number always starts with a -. 3. To fill the remaining characters of a field with 0s rather than spaces, place a 0 before the field width (and after the + if there is one), as in: f'[{27:+010d}]' 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. You can use JSON to serialize and deserialize objects to facilitate saving those objects to secondary storage and transmitting them over the Internet. 2. There are security vulnerabilities to serializing and deserializing data with the Python Standard Library's pickle module. 3. The with statement automatically releases a resource at the end of the statement's suite. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. A format string may contain multiple placeholders, in which case the format method's arguments correspond to the placeholders from left to right: '{} {}'.format('Amanda', 'Cyan') 2. The format string can reference specific arguments by their position in the format method's argument list, starting with position 0, as in: '{0} {0} {1}'.format('Happy', 'Birthday') You can reference each argument as often as you like and in any order. 3. You can reference keyword arguments by their keys in the placeholders, as in: '{first} {last}'.format(first='Amanda', last='Gray')'{last} {first}'.format(first='Amanda', last='Gray') 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. A regular expression string describes a search pattern for matching characters in other strings. 2. Regular expressions can help you extract data from unstructured text, such as social media posts. 3. Regular expressions are also important for ensuring that data is in the correct format before you attempt to process it. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. NumPy provides functions zeros, ones and full for creating arrays containing 0s, 1s or a specified value,respectively. 2. The first argument to the functions in Part (a) must be an integer or a tuple of integers specifying the desired dimensions. For an integer, each function re-turns a one-dimensional array with the specified number of elements. For a tuple of integers, these functions return a multidimensional array with the specified dimensions. 3. The array returned by NumPy function full contains elements with the second argument's value and type. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The array function copies its argument's dimensions and creates a new array. 2. The following creates an array from a two-row-by-three-column list:np.array([[1, 2, 3], [4, 5, 6]]) 3. NumPy auto-formats arrays, based on their number of dimensions, aligning the columns within each row. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The following code makes numbers2 a slice that views only the first three elements of numbers: import numpy as np numbers = np.arange(1, 6) numbers2 = numbers[0:3] 2. After the statement in Part (a) executes, numbers and numbers2 are different objects. 3. After the statement in Part (a) executes, modifying an element in numbers2 also modifies the corresponding element in numbers. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The json module's dumps function returns a Python string representation of an object in JSON format. 2. Using dumps with load, you can read JSON from a file and display it in a nicely indented format—sometimes called "pretty printing" the JSON. 3. When the dumps function call includes the indent keyword argument, as in with open('accounts.json', 'r') as accounts: print(json.dumps(json.load(accounts), indent=4)) the string contains newline characters and indentation for pretty printing—you also can use indent with the dump function when writing to a file. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. The re module's split function tokenizes a string, using a regular expression to specify the delimiter, and returns a list of strings. 2. The following code tokenizes a string by splitting it at any comma that's followed by 0 or more whitespace characters—\sis the whitespace character class and * indicates zero or more occurrences of the preceding subexpression: re.split(r',\s*', '1, 2, 3,4, 5,6,7,8') 3. The following code uses the keyword argument maxsplit to specify the maximum number of splits (in this case, after the 3 splits, the fourth string contains the rest of the original string): re.split(r',\s*', '1, 2, 3,4, 5,6,7,8', maxsplit=3) 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? 1. You can take a multidimensional array and flatten it into a single dimension with the methods flatten and ravel. 2. Method flatten deep copies the original array's data. 3. Modifying a flattened array does not modify the original array's data. 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? Assuming the following grades DataFrame: Wally Eva Sam Katie Bob Test1 87 100 94 100 83 Test2 96 87 77 81 65 Test3 70 90 90 82 85 1. One benefit of pandas is that you can quickly and conveniently look at your data in many different ways, including selecting portions of the data. 2. The following expression selects the 'Eva' column and returns it as a Series: grades['Eva'] 3. If a DataFrame's column-name strings are valid Python identifiers, you can use them as attributes. The following code selects the 'Sam' column using the Sam attribute: grades.Sam 4. All of the above statements are true.
4. All of the above statements are true.
Which of the following statements is false? In addition to validating data, regular expressions often are used to: 1. Extract data from text (sometimes known as scraping)—e.g., locating all URLs in a web page. 2. Clean data—for example, removing data that's not required, removing duplicate data, handling incomplete data, fixing typos, ensuring consistent data formats, dealing with outliers and more. 3. Transform data into other formats—for example, reformatting data that was collected as tab-separated or space-separated values into comma-separated values (CSV) format. 4. All of the above statements are true
4. All of the above statements are true.
An algorithm that tests whether the first array element is equal to any of the other array elements requires at most n - 1 comparisons, where n is the number of array elements. Which of the following statements is false? 1. If the array has 10 elements, this algorithm requires up to nine comparisons. 2. If the array has 1000 elements, it requires up to 999 comparisons. 3. As n grows larger, the n part of the expression n - 1 "dominates," and subtracting 1 becomes inconsequential. Big O is designed to highlight these dominant terms and ignore terms that become unimportant as n grows. 4. An algorithm that requires a total of n - 1 comparisons is said to be O(n - 1) and is said to have a linear run time.
4. An algorithm that requires a total of n - 1 comparisons is said to be O(n - 1) and is said to have a linear run time.
Suppose an algorithm is designed to test whether the first element of an array is equal to the second. If the array has 10 elements, this algorithm requires one comparison. If the array has 1000 elements, it still requires only one comparison. Which of the following statements is false? 1. The algorithm is completely independent of the number of elements in the array. 2. This algorithm is said to have a constant run time, which is represented in Big O notation as O(1) and pronounced as "order one." 3. An algorithm that's O(1) does not necessarily require only one comparison. O(1) simply means that the number of comparisons is constant—it does not grow as the size of the array increases. 4. An algorithm that tests whether the first element of an array is equal to any of the next three elements isO(3).
4. An algorithm that tests whether the first element of an array is equal to any of the next three elements isO(3).
Which of the following statements is false? 1. A class definition begins with the keyword class followed by the class's name and a colon (:). This line is called the class header. 2. The Style Guide for Python Code recommends that you begin each word in a multi-word class name with an uppercase letter (e.g., CommissionEmployee). 3. Every statement in a class's suite is indented. 4. Each class must provide a descriptive docstring in the line or lines immediately following the class header. To view any class's docstring in IPython, type the class name and a question mark, then press Enter.
4. Each class must provide a descriptive docstring in the line or lines immediately following the class header. To view any class's docstring in IPython, type the class name and a question mark, then press Enter.
Which of the following statements is false? 1. The re module's findall function finds every matching substring in a string and returns a list of the matching substrings. 2. The following code extracts all phone numbers of the form ###-###-#### from a string: contact = 'Wally White, Home: 555‐555‐1234, Work: 555‐555‐4321' re.findall(r'\d{3}‐\d{3}‐\d{4}', contact) 3. The re module's finditer function works like findall, but returns an iterable of match objects. 4. For large numbers of matches, using findall can save memory because it returns one match at a time, whereas finditer returns all the matches at once.
4. For large numbers of matches, using findall can save memory because it returns one match at a time, whereas finditer returns all the matches at once.
Which of the following statements is false? 1. By default, the following f-strings right-align the numeric values 27 and 3.5 and left-align the string"hello": f'[{27:10d}]' f'[{3.5:10f}]' f'[{"hello":10}]' 2. Python formats float values with six digits of precision to the right of the decimal point by default. 3. For formatted values that have fewer characters than the field width, the remaining character positions are filled with spaces. 4. Formatted values with more characters than the fieldwidth cause a ValueError.
4. Formatted values with more characters than the fieldwidth cause a ValueError.
Which of the following statements about DataFrames and the Titanic dataset is false? 1. For large datasets, displaying the DataFrame shows only the first 30 rows, followed by "..." and the last 30 rows. 2. To save space, we can view the first five and last five rows with DataFrame methods head and tail. Both methods return five rows by default, but you can specify the number of rows to display as an argument. 3. Pandas adjusts each column's width, based on the widest value in the column or based on the column name, which is wider. 4. If the value in a column of a row is NaN (not a number) that indicates a value, which is not a legal number in the dataset.
4. If the value in a column of a row is NaN (not a number) that indicates a value, which is not a legal number in the dataset.
Which of the following statements is false? 1. A try statement can have a finally clause as its last clause after any except clauses or else clause. 2. The finally clause is guaranteed to execute, regardless of whether its try suite executes successfully or an exception occurs. 3. In other languages that have finally, the finally suite is an ideal location to place resource-deallocation code for resources acquired in the corresponding try suite. 4. In Python, we prefer the else clause of a try statement for resource-deallocation code and place other kinds of "clean up" code in the finally suite.
4. In Python, we prefer the else clause of a try statement for resource-deallocation code and place other kinds of "clean up" code in the finally suite.
Based on the string, which of the following statements is false? sentence = '\t \n This is a test string. \t\t \n' 1. There are several string methods for removing whitespace from the ends of a string. Because strings are immutable each returns a new string leaving the original unmodified. 2. The following code uses string method strip to remove the leading and trailing whitespace from sentence:sentence.strip() 3. The following code snippets first use method lstrip to remove only leading whitespace from sentence: sentence.lstrip() then use method rstrip to remove only trailing whitespace: sentence.rstrip() 4. Methods strip, lstrip and rstrip remove only leading and/or trailing spaces.
4. Methods strip, lstrip and rstrip remove only leading and/or trailing spaces.
To create a Decimal object, we can write: value =Decimal('3.14159') This is known as a(n) ________ expression because it builds and initializes an object of the class. 1. builder 2. maker 3. assembler 4. constructor
4. constructor
Views are also known as _________ copies. 1. deep 2. secondary 3. reliant 4. shallow
4. shallow