CIT 486 Final Exam
What should the question mark (?) in the following for statement be replaced with, so that the statements will calculate 5!: In [1]: factorial = 1 In [2]: for number in range(5, 0, ?): ...: factorial *= number ...: In [3]: factorial Out[3]: 120
-1
The value of the expression of: In [1]: floor(-3.14159)
-4.0
What does the following for statement print? for counter in range(4): print(counter, end=' ')
0 1 2 3
By default, the re module's sub function replaces only the first occurrence of a pattern with the replacement text you specify. The statement re.sub(r'\t', ', ', '1\t2\t3\t4') returns '1, 2\t3\t4'
False
The following code creates a list, then uses del to remove its first element: numbers = list(range(0, 10))del numbers[1]
False
The following code formats the float value 17.489 rounded to the hundredths position: '{:.3f}'.format(17.489)
False
The following code replaces tab characters with commas: values = '1\t2\t3\t4\t5'values.replace('\t', ', ')
False
Two sets are disjoint if they do not have any common elements. You can determine this with the set type's isdisjoint method. What values are actually displayed for ??? in Out[1] and Out[2]: In [1]: {1, 3, 5}.isdisjoint({2, 4, 6})Out[1]: ???In [2]: {1, 3, 5}.isdisjoint({4, 6, 1})Out[2]: ???
True, False
Which of the following statements is false? Tuples are immutable. Tuples must store heterogeneous data. A tuple's length is its number of elements. A tuple's length cannot change during program execution.
Tuples must store heterogeneous data.
Lists may store ________ data, that is, data of many different types.
heterogeneous
Fill in the missing code below to replace the *** for ***: print('$') So that when you execute the code, it displays: $ $ $ $
in range(4)
The following code implements a simple linear search. In [1]: def linear_search(data, search_key): ...: for index, value in enumerate(data):: ...: if value == search_key: ...: return ? ...: return -1 ...: ...: In the statement return ?, what should the ? be?
index
The json module's function reads the entire JSON contents of its file object argument and converts the JSON into a Python object. This is known as the data.
load, deserializing
Write the statement that creates a slice consisting of the elements at indices 2 through 6 of a numbers: numbers = [2, 3, 5, 7, 11, 13, 17, 19]
numbers[2:6]
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.
reading only
We use array method ________ to produce two-dimensional arrays from one-dimensional ranges.
reshape
What is the output of the following code for Out[5]: In [4]: x = 'dog'In [5]: type(x)Out[5]:
str
If numbers is a five-element integer array, numbers * 2 is equivalent to: numbers * [2, 2, 2, 2, 2]
True
Sets may contain only immutable objects, like strings, ints, floats and tuples that contain only immutable elements.
True
Which of the following statements about sorting unique items is false? Sorting data (i.e., placing the data in a particular order—ascending or descending—is one of the most important types of computing applications. 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. 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. All of the above statements are true.
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.
Preparing data for analysis is called or .
Both (a) and (b).
Which of the following statements is false? -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. -The simplest and most apparent algorithms often perform poorly—developing more sophisticated algorithms can lead to superior performance. -All of the above statements are true. -None of the above statements are true.
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.
Based on the string sentence = '\t \n This is a test string. \t\t \n' 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()
True
When you call describe on a DataFrame containing both numeric and non-numeric columns, describe calculates the statistics below only for the numeric columns.
True
Which of the following statements is false? -Searching data involves determining whether a value (referred to as the search key) is present in the data and, if so, finding its location. -Two popular search algorithms are the simple binary search and the faster but more complex linear search. -Sorting places data in ascending or descending order, based on one or more sort keys. Each of the above statements is true.
Two popular search algorithms are the simple binary search and the faster but more complex linear search.
Which of the following statements is incorrect: min(17, 19, 23, 29, 31, 37, 43) is a valid call to built-in function min, The range of values is simply the minimum through the maximum value. Much of data science is devoted to getting to know your data. All of the above are correct.
All of the above are correct.
Based on the following function definition that can receive an arbitrary number of arguments: In [1]: def average(*args):...: return sum(args) / len(args)...: which of the following statements is false?
All of the above are true.
Which of the following statements is false? -You can create an array from a range of elements, then use array method reshape to transform the one-dimensional array into a multidimensional array. -The following code creates an array containing the values from 1 through 20, then reshapes it into four rows by five columns: np.arange(1, 21).reshape(4, 5) -A 24-element one-dimensional array can be reshaped into a 2-by-12, 8-by-3 or 4-by-8 array, and vice versa. -All of the above are true.
All of the above are true.
Assuming the following DataFrame grades: Wally Eva Sam Katie BobTest1 87 100 94 100 83Test2 96 87 77 81 65Test3 70 90 90 82 85 Which of the following statements is false? -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. -The following expression selects 'Eva' column and returns it as a Series: grades['Eva'] -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 -All of the above statements are true.
All of the above statements are true
Which of the following statements about the IPython session below is true? In [1]: gender = 'Female' In [2]: age = 70 In [3]: if gender == 'Female' and age >= 65: ...: print('Senior female') ...: Senior female
All of the above statements are true
Which of the following statement(s) will reverse the order of the below items list numbers: numbers = [2, 3, 4, 6, 7, 13, 17, 19] -reversed_numbers = [item for item in reversed(numbers)] -The following code concisely creates a new list in reverse order: numbers[::-1] -To sort a list in descending order, call list method sort with the optional keyword argument reverse=True. numbers.sort(reverse=True) -All of the above statements are true.
All of the above statements are true.
Which of the following statements is false? -If randrange truly produces integers at random, every number in its range has an equal probability (or chance or likelihood) of being returned each time we call it. -We can use Python's underscore (_) digit separator to make a value like 3000000 more readable as 3_000_000. -The expression range(6,000,000) would be incorrect. Commas separate arguments in function calls, so Python would treat range(6,000,000) as a call to range with the three arguments 6, 0 and 0. -All of the above statements are true.
All of the above statements are true.
Which of the following are reasons why Python is popular and everyone should consider learning it: -It's open source, free and widely available with a massive open-source community. -It's easier to learn than languages like C, C++, C# and Java, enabling novices and professional developers to get up to speed quickly. -It's easier to read than many other popular programming languages. -All of the above.
All of the above.
Replace the ??? in the following comprehension statement to include in list4 only the even values produced by the for clause: list4 = [item for item in range(1, 11) if item ???]
% 2 == 0
What does the following for statement print? for counter in range(10): print(counter, end=' ')
0 1 2 3 4 5 6 7 8 9
What does the following line of code display? print(10, 20, 30, sep=', ')
10, 20, 30
Which of the following would be accepted by a program strictly looking for four integers of data in CSV format?
100,85, 77,9
Which of the following statements is false? A function definition begins with the def keyword, followed by the function name, a set of parentheses and a semicolon (;). When you change a function's code, all calls to the function execute the updated version. The following code calls square first, then print displays the result: print('The square of 7 is', square(7)) The required parentheses contain the function's parameter list—a comma-separated list of parameters representing the data that the function needs to perform its task.
A function definition begins with the def keyword, followed by the function name, a set of parentheses and a semicolon (;).
Which of the following statements is false? -A string delimited by single quotes may include double-quote characters: print('Display "hi" in quotes') -A string delimited by double quotes may include single quote characters: print("Display the name O'Brien") -A string delimited by double quotes may not include double quotes. -To avoid using \' and \" inside strings, you can enclose such strings in triple quotes: print(""""Display the name O'Brien"""")
A string delimited by double quotes may not include double quotes.
Consider the following code: In [1]: s1 = 'happy' In [2]: s2 = 'birthday' In [3]: s1 += ' ' + s2 In [4]: s1Out[4]: 'happy birthday' In [5]: symbol = '>' In [6]: symbol *= 5 In [7]: symbolOut[7]: '>>>>>' Which snippet(s) in this interactive session appear to modify existing strings, but actually create new string objects?
Both snippets [3] and [6].
Which of the following statements is false? -DataFrames have a describe method that calculates basic descriptive statistics for the data and returns them as two-dimensional array. -In a DataFrame, the statistics are calculated by column. -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. -You can control the precision of floating-point values and other default settings with pandas' set_option function.
DataFrames have a describe method that calculates basic descriptive statistics for the data and returns them as two-dimensional array.
Which of the following statements is false? The following if statement uses the == comparison operator to determine whether the values of variables number1 and number2 are equal: if number1 == number2:print(number1, 'is equal to', number2) Each if statement consists of the keyword if, the condition to test, and a colon (:) followed by an indented body called a suite. Each suite contains zero or more statements. Forgetting the colon (:) after the condition is a common syntax error.
Each suite contains zero or more statements.
Which of the following statements is false? -String method split with no arguments tokenizes a string by breaking it into substrings at each whitespace character, then returns a list of tokens. -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(', ') -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'] -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.
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']
Based on the following function definition: def rectangle_area(length, width):"""Return a rectangle's area.""" return length * width The following call results in results in TypeError because the order of keyword arguments matters—they need to match the corresponding parameters' positions in the function definition: rectangle_area(width=5, length=10)
False
The following code creates a Series of student grades from a list of integers: import pandas as pdgrades = pd.Series([87, 100, 94]) By default, a Series has integer indexes numbered sequentially from 1, and the Series argument may be a tuple, a dictionary, an array, another Series or a single value.
False
The following code creates a dictionary with the country-name keys 'Finland', 'South Africa' and 'Nepal' and their corresponding Internet country code values 'fi', 'za' and 'np': country_codes = {'Finland', 'fi', 'South Africa', 'za', 'Nepal', 'np'}
False
The following code produces 10 random integers in the range 1-6 to simulate rolling a six-sided die: import randomfor roll in range(10):print(random.randrange(1, 6), end=' ')
False
The following session calls the string object s's object's lower and upper methods, which produce new strings containing all-lowercase and all-uppercase versions of the original string, leaving s unchanged: In [1]: s = 'Hello'In [2]: s.lower() # call lower method on string object sOut[2]: 'hello'In [3]: s.upper()Out[3]: 'HELLO' After the preceding session, s contains 'HELLO'.
False
Which of the following statements is false? The argument of each of the functions mean, median and mode must be an iterable. To help confirm the median and mode values of a grades list, you can use the built-in sorted function to get a copy of grades with its values arranged in increasing order, as in the following session, which makes it clear that both the median and the mode are 85: In [1]: grades = [85, 93, 45, 89, 85] In [2]: sorted(grades) Out[2]: [45, 85, 85, 89, 93] If a list's number of values is even, median returns the mode of the two middle values. The mode function causes a StatisticsError for lists like [85, 93, 45, 89, 85, 93] in which there are two or more "most frequent" values. Such a set of values is said to be bimodal.
If a list's number of values is even, median returns the mode of the two middle values.
Which of the following statements is false? -Python applies the operators in arithmetic expressions according to the rules of operator precedence, which are generally the same as those in algebra. -Parentheses have the highest level of precedence, so expressions in parentheses evaluate first—thus, parentheses may force the order of evaluation to occur in any sequence you desire. -In expressions with nested parentheses, such as (a / (b - c)), the expression in the innermost parentheses (that is, b - c) evaluates first. -If an expression contains several exponentiation operations, Python applies them from left to right.
If an expression contains several exponentiation operations, Python applies them from left to right.
Which of the following statements is false? Using the equality operator == instead of the assignment symbol = in an assignment statement can lead to subtle problems. If instead of defining a variable grade with the assignment: grade = 85 we accidentally write: grade == 85 then grade would be undefined and we'd get a NameError. If grade had been defined before the statement grade == 85, the statement would evaluate to True or False, depending on grade's value, and not perform the intended assignment—fortunately, this is harmless. All of the above statements are true.
If grade had been defined before the statement grade == 85, the statement would evaluate to True or False, depending on grade's value, and not perform the intended assignment—fortunately, this is harmless.
Which of the following statements are false? -JSON (JavaScript Object Notation) is a data-interchange format readable only by computers and used to represent objects (such as dictionaries, lists and more) as collections of name-value pairs. -Many libraries you'll use to interact with cloud-based services such as Twitter, IBM Watson and others communicate with your applications via JSON objects. -JSON can represent objects of custom classes. -JSON has become the preferred data format for transmitting objects across platforms. This is especially true for invoking cloud-based web services, which are functions and methods that you call over the Internet.
JSON (JavaScript Object Notation) is a data-interchange format readable only by computers and used to represent objects (such as dictionaries, lists and more) as collections of name-value pairs.
The following update call receives a dictionary key-value pair to insert or update: country_codes.update({'Australia': 'ar'}) Provided an incorrect country code for Australia. The following code corrects this by using a keyword argument to update the value associated with 'Australia': country_codes.update(Australia='au')
True
Which of the following statements is false? -NumPy arrays use only zero-based integer indexes. -Like arrays, Series use only zero-based integer indexes. -Series may have missing data, and many Series operations ignore missing data by default. -All of the above statements are true.
Like arrays, Series use only zero-based integer indexes.
Which of the following statements is false? -You can delete a key-value pair from a dictionary with the del statement -You can remove a key-value pair with the dictionary method pop, which returns the value for the removed key. -Method clean deletes the dictionary's key-value pairs: -Operators in and not in can determine whether a dictionary contains a specified key.
Method clean deletes the dictionary's key-value pairs:
Which of the following statements is true with respect to displaying an array of 1000 items or more?
NumPy drops the middle rows, middle columns or both from the output.
Which of the following statements is false? -Pandas is the most popular library for dealing with mixed data types, customized indexing, missing data, and data that needs to be manipulated into forms appropriate for the databases and data analysis packages. -Data science presents unique demands for which more customized data structures are required. -NumPy's array is optimized for heterogeneous numeric data that's accessed via integer indices. -Pandas provides two key collections—Series for one-dimensional collections and DataFrames for two-dimensional collections.
NumPy's array is optimized for heterogeneous numeric data that's accessed via integer indices.
Which of statements a), b) or c) is false? -A variable name, such as x, is an identifier. -Each identifier may consist of letters, digits and underscores (_) but may not begin with a digit. -Python is case insensitive, so number and Number are the same identifier despite the fact that one begins with a lowercase letter and the other begins with an uppercase letter. -All of the above statements are true.
Python is case insensitive, so number and Number are the same identifier despite the fact that one begins with a lowercase letter and the other begins with an uppercase letter.
When using IPython in interactive mode to evaluate a simple arithmetic expression in a new session, which of the following is false? The text "In [1]:" is a prompt, indicating that IPython is waiting for your input. You can type ? for help or you can begin entering snippets After you type an expression like 45 + 72 and press Enter, IPython reads the snippet, evaluates it and prints its result in Out[1]:. Then IPython displays the In [2] prompt to show that it's waiting for you to enter your second snippet Python uses x for multiplication and the forward slash (/) for division.
Python uses x for multiplication and the forward slash (/) for division.
Which of the following statements is false? -As in lists and arrays, the first character in a text file and byte in a binary file is located at position 0, so in a file of n characters or bytes, the highest position number is n - 1. -Python views text files and binary files (for images, videos and more) as sequences of bytes. -For each file you open, Python creates a file object that you'll use to interact with the file. -All of the above statements are true.
Python views text files and binary files (for images, videos and more) as sequences of bytes.
Which of the following statements about libraries is false? -Using existing libraries helps you avoid "reinventing the wheel," thus leveraging your program-development efforts. -Rather than developing lots of original code—a costly and time-consuming process—you can simply create an object of a pre-existing library class, which takes only three Python statements. -Libraries help you perform significant tasks with modest amounts of code. -All of the above statements are false.
Rather than developing lots of original code—a costly and time-consuming process—you can simply create an object of a pre-existing library class, which takes only three Python statements.
Which of the following statements is false? -You can determine the number of items in a set with the built-in len function. -Sets are not iterable, so you cannot process each set element with a for loop. -You can check whether a set contains a particular value using the in and not in operators. -Sets are unordered, so there's no significance to the iteration order.
Sets are not iterable, so you cannot process each set element with a for loop.
Which of the following statements is false? -The while statement allows you to repeat one or more actions while a condition remains True. Such a statement often is called a loop. -The following code finds the first power of 3 larger than 50: product = 3while product < 50:product = product * 3 -Something in a while statement's suite must ensure that the condition eventually becomes False. Otherwise, a logic error called an infinite loop occurs. -In applications executed from a Terminal, Command Prompt or shell, type Ctrl + c or control + c (depending on your keyboard) to terminate an infinite loop.
The following code finds the first power of 3 larger than 50: product = 3while product < 50:product = product * 3
The names keyword argument specifies the DataFrame's column names. If you do not supply the names keyword argument, read_csv assumes that the CSV file's first row is a comma-delimited list of column names.
True
Consider this text from Shakespeare: soliloquy = 'To be or not to be, that is the question' Which of the following statements is false?
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? The following assignment statement adds the values of variables x and y and assigns the result to the variable total: total = x + y The preceding snippet is read, "total is assigned the value of x + y." The = symbol is the assignment operator. The right side of the = symbol always executes first, then the result is assigned to the variable on the symbol's left side.
The = symbol is the assignment operator.
Which of the following statements is false? -The d presentation type in the following f-string formats strings as integer values: f'{10:d}' -The integer presentation types b, o and x or X format integers using the binary, octal or hexadecimal number systems, respectively. -The c presentation type in the following f-string formats an integer character code as the corresponding character: f'{65:c} {97:c}' -If you do not specify a presentation type, as in the second placeholder below, non-string values like the integer 7 are converted to strings: f'{"hello":s} {7}'
The d presentation type in the following f-string formats strings as integer values: f'{10:d}'
Which of the following statements is false? -True division (/) divides a numerator by a denominator and yields a floating-point number with a decimal point. Floor division (//) divides a numerator by a denominator, yielding the highest integer that's not greater than the result. Python truncates (discards) the fractional part. -The expression -13 / 4 evaluates to -3.25. -The expression -13 // 4 evaluates to -3.
The expression -13 // 4 evaluates to -3.
Which of the following statements is false. You can import all identifiers defined in a module with a wildcard import of the form from modulename import * A wildcard import makes all of the module's identifiers available for use in your code. The following session is an example of safe use of a wildcard import: In [1]: e = 'hello'In [2]: from math import *In [3]: eOut[3]: 2.718281828459045 Importing a module's identifiers with a wildcard import can lead to subtle errors—it's considered a dangerous practice that you should avoid.
The following code calls function square twice. The first call produces the int value 49 and the second call produces the int value 0: In [1]: def square(number):...: """Calculate the square of a number.""" ...: return number ** 2 ...: In [2]: square(7)Out[2]: 49In [3]: square(.1)Out[3]: 0
Which of the following statements is false? -Each function should perform a single, well-defined task. -The following code calls function square twice. The first call produces the int value 49 and the second call produces the int value 0: In [1]: def square(number):...: """Calculate the square of a number.""" ...: return number ** 2 ...: In [2]: square(7)Out[2]: 49In [3]: square(.1)Out[3]: 0 -The statements defining a function arewritten only once, but may be called "to do their job" from many points in a program and as often as you like. -Calling square with a non-numeric argument like 'hello' causes a TypeError because the exponentiation operator (**) works only with numeric values.
The following code calls function square twice. The first call produces the int value 49 and the second call produces the int value 0: In [1]: def square(number):...: """Calculate the square of a number.""" ...: return number ** 2 ...: In [2]: square(7)Out[2]: 49In [3]: square(.1)Out[3]: 0
Which of the following statements is false? The descriptive statistics mean, median and mode are measures of central tendency—each is a way of producing a single value that is in some sense typical of the others. The following session creates a list called grades, then uses the built-in sum and len functions to calculate the median "by hand"—sum calculates the total of the grades (397) and len returns the number of grades (5): In [1]: grades = [85, 93, 45, 89, 85] In [2]: sum(grades) / len(grades) Out[2]: 79.4 Like functions min and max, sum and len are both examples of functional-style programming reductions—they reduce a collection of values to a single value. The Python Standard Library's statistics module provides functions for calculating the mean, median and mode—these, too, are reductions.
The following session creates a list called grades, then uses the built-in sum and len functions to calculate the median "by hand"—sum calculates the total of the grades (397) and len returns the number of grades (5): In [1]: grades = [85, 93, 45, 89, 85] In [2]: sum(grades) / len(grades) Out[2]: 79.4
Which of the following statements is false? Function range's one-argument version produces a sequence of consecutive integers from 0 up to, but not including, the argument's value. The following snippet produces the sequence 5 6 7 8 9. for number in range(5, 10):print(number, end=' ') The following snippet produces the sequence 0 2 4 6 8. for number in range(0, 10, 2):print(number, end=' ') The following snippet produces the sequence 10 8 6 4 2 0. for number in range(10, 0, -2):print(number, end=' ')
The following snippet produces the sequence 10 8 6 4 2 0. for number in range(10, 0, -2):print(number, end=' ')
In the following code segment: # process 10 students for student in range(10): # get one exam result result = int(input('Enter result (1=pass, 2=fail): ')) if result == 1: passes = passes + 1 else: failures = failures + 1
The if statement is nested in the for statement.
Which of the following statements is false? -Augmented assignments abbreviate assignment expressions in which the same variable name appears on the left and right of the assignment's =, as total does in: for number in [1, 2, 3, 4, 5]:total = total + number -The following code re-implements the preceding for statement using an addition augmented assignment (+=) statement: for number in [1, 2, 3, 4, 5]:total += number -The statement f = f ** 3 may be replaced by the more concise augmented assignment statement f *= 3. -All of the above statements are true.
The statement f = f ** 3 may be replaced by the more concise augmented assignment statement f *= 3.
Which of the following statements about DataFrames is false? -The index can be a slice. In the following slice containing, the range specified includes the high index ('Test3'): grades.loc['Test1':'Test3'] -When using slices containing integer indices with iloc, the range you specify excludes the high index (2): grades.iloc[0:2] -To select specific rows, use a tuple rather than slice notation with loc or iloc. -All of the above statements are true.
To select specific rows, use a tuple rather than slice notation with loc or iloc.
A dictionary is an unordered collection which stores key-value pairs that map immutable keys to values, just as a conventional dictionary maps words to definitions.
True
Assuming the following DataFrame grades: Wally Eva Sam Katie BobTest1 87 100 94 100 83Test2 96 87 77 81 65Test3 70 90 90 82 85 To see the average of all the students' grades on each test, call mean on the T attribute: grades.T.mean()
True
Assuming the following DataFrame grades: Wally Eva Sam Katie BobTest1 87 100 94 100 83Test2 96 87 77 81 65Test3 70 90 90 82 85 rather than getting the summary statistics by student, you can get them by test. Simply call describe on grades.T, as in: grades.T.describe()
True
Assuming the following array grades: grades = np.array([[87, 96, 70], [100, 87, 90], [94, 77, 90], [100, 81, 82]]) To select multiple sequential rows, use slice notation, as in grades[0:2] and to select multiple non-sequential rows, use a list of row indices, as in grades[[1, 3]]
True
Based on the string sentence = '\t \n This is a test string. \t\t \n' 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:
True
Consider a Series of hardware-related strings: hardware = pd.Series(['Hammer', 'Saw', 'Wrench']) The following code calls string method contains on each element to determine whether the value of each element contains a lowercase 'a': hardware.str.contains('a') and returns a Series containing bool values indicating the contains method's result for each element.
True
Consider a Series of hardware-related strings: hardware = pd.Series(['Hammer', 'Saw', 'Wrench']) The following code uses the Series str attribute to invoke string method upper on every Series element, producing a new Series containing the uppercase versions of each element in hardware: hardware.str.upper()
True
Element-wise operations are applied to every array element, so given an integer array named numbers, the expression numbers * 2 multiplies every element by 2, and the expression numbers ** 3 cubes every element.
True
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)
True
The array methods sum, min, max, mean, std (standard deviation) and var (variance) are each functional-style programming reductions.
True
The following IPython session loads and displays the CSV file accounts.csv: In [1]: import pandas as pdIn [2]: df = pd.read_csv('accounts.csv', ...: names=['account', 'name', 'balance'])...:In [3]: dfOut[3]: account name balance0 100 Jones 24.981 200 Doe 345.672 300 White 0.003 400 Stone -42.164 500 Rich 224.62 The names keyword argument specifies the DataFrame's column names. If you do not supply the names keyword argument, read_csv assumes that the CSV file's first row is a comma-delimited list of column names.
True
The following code creates an accounts.txt file and write five client records to the file. Generally, records in text files are stored one per line, so we end each record with a newline character: with open('accounts.txt', mode='w') as accounts:accounts.write('100 Jones 24.98\n')accounts.write('200 Doe 345.67\n')accounts.write('300 White 0.00\n')accounts.write('400 Stone -42.16\n')accounts.write('500 Rich 224.62\n') You can also write to a file with print (which automatically outputs a \n), as in print('100 Jones 24.98', file=accounts)
True
The following code creates the dictionary roman_numerals, which maps roman numerals to their integer equivalents (the value for 'X' is intentionally wrong): roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'V': 5, 'X': 100} Replacing the value associated with the key 'X' with a new value 10, can be done by the following statement: In [1]: roman_numerals['X'] = 10
True
The following code produces different values are likely to be displayed each time you run the code: import randomfor roll in range(10):print(random.randrange(1, 6), end=' ')
True
The following code, which has a dictionary with unique values, reverses the key-value pairs: months = {'January': 1, 'February': 2, 'March': 3}months2 = {number: name for name, number in months.items()}
True
The following statements replaced the results of the four list comparisons below with blank. What are those output values for Out [4], Out [5], Out[6] and Out[7]. Type your answers for each output respectively. In [1]: a = [1, 2, 3]In [2]: b = [1, 2, 3]In [3]: c = [1, 2, 3, 4] In [4]: a == b Out[4]: In [5]: a == c Out[5]: In [6]: a < c Out[6]: In [7]: c >= b Out[7]:
True False True True
In the following interactive session that compares the strings 'Orange' and 'orange': In [1]: 'Orange' == 'orange'Out[1]: False In [2]: 'Orange' != 'orange'Out[2]: ??? In [3]: 'Orange' < 'orange'Out[3]: True In [4]: 'Orange' <= 'orange'Out[4]: True In [5]: 'Orange' > 'orange'Out[5]: False In [6]: 'Orange' >= 'orange'Out[6]: ??? The outputs of snippets [2] and [6] (marked as ???) respectively are:
True False
Which of the following statements is false? -Python requires you to indent the statements in suites. -Incorrect indentation of the statements in a suite can cause errors. -Using the assignment symbol (=) instead of the equality operator (==) in an if statement's condition is a common logic error. -Using == in place of = in an assignment statement can lead to subtle problems.
Using the assignment symbol (=) instead of the equality operator (==) in an if statement's condition is a common logic error.
Which of the following statements is false? -Variables, lists, tuples, dictionaries, sets, arrays, pandas Series and pandas DataFrames offer long-term data storage. -Computers store files on secondary storage devices, including solid-state drives, hard disks and more. -Some popular text file formats are plain text, JSON (JavaScript Object Notation) and CSV (comma-separated values). -All of the above statements are true.
Variables, lists, tuples, dictionaries, sets, arrays, pandas Series and pandas DataFrames offer long-term data storage.
Which of the following statements is false? -When you evaluate expressions in interactive mode, the text that print displays is preceded by Out[] with a snippet number in the square brackets. -print does not display a string's quotes, though there is a way to display quotes in strings. -You also may enclose a string in double quotes ("), as in: print("Welcome to Python!") but Python programmers generally prefer single quotes. -When print completes its task, it positions the screen cursor at the beginning of the next line.
When you evaluate expressions in interactive mode, the text that print displays is preceded by Out[] with a snippet number in the square brackets.
For variables x = 'a' and y = 'b', what will the following statement display: print((x + y), 'and', (y + x))
ab and ba
What is the output of the following code: min('yellow', 'red', 'orange', 'blue', 'green')
blue
Consider the list color_names: color_names = ['orange', 'yellow', 'green'] Write the statement that uses the insert method to insert 'red' at index 0.
color_names.insert(0, 'red')
List comprehensions can replace many for statements that iterate over existing sequences and create new lists, such as: list1 = [] for item in range(1, 6): Write the statement that can accomplish the same task in a single line of code with a list comprehension:
list1 = [item for item in range(1, 6)]
Assume the following array definitions: import numpy as npintegers = np.array([[1, 2, 3], [4, 5, 6]])floats = np.array([0.0, 0.1, 0.2, 0.3, 0.4]) The attribute contains an array's number of dimensions and the attribute contains a specifying an array's dimensions:
ndim, shape, tuple
Fill in the missing code to replace *** in the following code with a statement : if grade >= 90: *** so that will print a message like:'Congrats! Your grade of 91 is A '. Your statement should print the value already entered and stored to a variable grade = 91
print('Congrats! Your grade of', grade, 'is A')
Fill in the missing code to replace *** in the following code with a statement in a function that calculates the square of its argument: def square(number): ***
return number ** 2
Assume x is 3, y is 7.1 and z is '11.5'. Which of the following statements is incorrect?
the value of z is 11.5
The following creates an array from a _________-row-by-_________-column list: np.array([[1, 2, 3], [4, 5, 6]])
two three
The following lists contain names and the grade point average of that name respectively: names = ['Bob', 'Sue', 'Amanda'] grade_point_averages = [3.5, 4.0, 3.75] Write the zip call statement that produces the tuples ('Bob', 3.5), ('Sue', 4.0) and ('Amanda', 3.75) consisting of the elements at index 0, 1 and 2 of each list, respectively:
zip(names, grade_point_averages)
Which of the following would be displayed for ??? by Out[3]? In [1]: numbers = list(range(10)) + list(range(5))In [2]: numbersOut[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]In [3]: set(numbers)Out[3]: ???
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}