S364
Each item in a dictionary is a key/value pair a sequence a string a list
a key/value pair
What method is used to create a matplotlib Bar Chart? plt.plot() plt.bar() plt.pie() plt.column()
plt.bar()
To create a datetime object by parsing a string, you can use the strftime() method of the date class parse() method of the datetime class strParse() method of the datetime class strptime() method of the datetime class
strptime() method of the datetime class
The following code would be considered what kind of NumPy array? import numpy as np arr = np.array([[1, 3, 5], [2, 4, 6], [5,6,7]]) 1-dimensional 2-dimensional 3-dimensional This will be a Tuple
2-dimensional
How many items does the following dictionary contain? flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} 1 3 6 7
3
What is the value of my_num after the following statement executes? my_num = (50 + 2 * 10 - 4) / 2 258 33 156 29
33
The code below creates a set with _____ values/items. set_2 = {1, 2, 3, 4, 4} 3 4 5 None of the choices are correct.
4
def get_volume(width, height, length=2): volume = width * height * length return volume def main(): l = 3 w = 4 h = 5 v = get_volume(l, w, h) print(v) if __name__ == "__main__": main() What value is passed to the height argument by the call to the get_volume() function? 2 3 4 5
4
Given: x = 23 , y = 15 What is the value of new_num after the following statement executes? new_num = x % y 1 1.533333 .533333 8
8
What will be displayed after the following code executes? book_name = "a tale for the knight"book = book_name.title()print(book) A Tale For The Knight A Tale for the Knight A Tale for the knight A tale for the knight
A Tale For The Knight
To concatenate two string variables you can use what symbols/characters? : -- + =
+
Valid functions and methods used with sets include the following except len() .add() .len() .insert()
.insert()
To order a list into an alphabetical order or sequential order we can use what method? .sort() .order() .sequence() .alphabatize()
.sort()
Python is considered a good first language to learn because: it has a simple syntax Powerful for all-purpose programming All of the choices are True Programs can be written quickly.
All of the choices are True
Which among the following options can be used to create a Data Frame in Pandas? A NumPy array A dictionary A list All of the other options can be used to create a Pandas Data Frame
All of the other options can be used to create a Pandas Data Frame
The following code would result in a ______ with _____ items in it. thisset = set("apple", "banana", "cherry", "peach") list ; 4 dictionary; 2 set; 4 An error would occur with this code.
An error would occur with this code.
Which type of expression has a value of either true or false? relational binary Boolean if-else
Boolean
All of the following are true of a Python Set except: All items must be unique Set is unordered Elements cannot be of different data types can contain multiple values/items
Elements cannot be of different data types
Clustering algorithms require a gold-standard dataset to train and run. True False
False
If custom row indexes and customer column titles are not provided the index and column titles will default to "blanks" or Null values.
False
Pandas does not have it's own built in Statistical functions and we have to use other libraries or modules to perform statistical analysis. True Flase
False
Since NumPy arrays can only have one data type in an array the following code would cause a Run-time error (not work). import numpy as np arr_a = np.array([1, "2", 0]) True False
False
The .info() method of the Pandas Data Frame will provide the number of NULL values found in each column of data. True False
False
The following code creates a NumPy list of integers. import numpy as np arr_a = np.array([1, 2, 0.0]) True False
False
The following code will print a Pandas Data Frame sorted by the column A data = np.random.normal(1, 1, (4, 4)) # mean = 0, std = 1, 3 x 3 row = ["N", "S", "E", "W"] col = ['A', 'B', 'C', 'D'] frame = pd.DataFrame(data, index=row, columns=col) frame.sort_values(by=['A']) print(frame)
False
The following code would cause an run-time error (would not work). a = np.array([1, 3, 5]) b = np.array([6]) True False
False
The following line of code will fill in NULL values with the mean of the entire column. df5 = df2.fillna(df.average(), inplace=False) True False
False
To use MatPlotLib graphs in Python the data must first be in the form of a Pandas Dataframe, Pandas Series or NumPy array? True False
False
What will the output be for the following code: set_1 = {"Accord", "Civic", "Clarity", "Insight", "CR-V", "Passport", "Pilot"} set_2 = {"Accord", "Civic", "Clarity"} set_3 = {"Insight", "CR-V", "Passport", "Pilot"} print(set_3 <= set_2)print(set_1 >= set_3) True/True False/False True/False False/True
False/True
To print the first 5 rows of the following Pandas Data Frame we use df = d.read_csv("Salaries.csv") df.head() df.tail() df.head(5) df.tail(5) More than one of the options would work.
More than one of the options would work.
To view/display the column names of a Pandas Data Frame called 'df' (see below), we can use what code? import pandas as pd # intialise data of lists. data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Create DataFrame df = pd.DataFrame(data) print(df.info()) print(df.describe()) print(df.columns) print(df) All of the print statements will work More than one of the print statement will work
More than one of the print statement will work
To print out the first row of the following NumPy array I could use import numpy as np b = np.array([[5, 3, 1], [2, 4, 6]]) print(b[0, :]) print(b[:]) print(b(0)) print(b[0]) More than one of these options would work
More than one of these options would work
In the code below, the only values that will occur in the new column called "Column 10 Binned" will be ... randArray = np.random.randint(1,12,(5,10))df6 = pd.DataFrame(randArray,index=["R1","R2","R3","R4","R5"], columns=["col1","col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9", "col10", ]) binranges = [0, 3, 6, 10]labelnames = ["low", "med", "high"]df6['Column 10 Binned'] = pd.cut(df6['col10'], bins=binranges, labels=labelnames) 0, 3, 6, 10 "low", "med", "high" 0, "low", "med", "high" NaN, "low", "med", "high"
NaN, "low", "med", "high"
Which of the following is not a reserved word in Python? (Hint: It could be used as the name of a variable.) pass Number import break
Number
The correct order of operation in programming (a.k.a. Precedence Rules) is the following: Parenthesis, Power, Multiplication, Addition, Left to Right Left to Right, Parenthesis, Power, Multiplication, Addition Power, Parenthesis, Multiplication, Addition, Left to Right Parenthesis, Power, Multiplication, Left to Right, Addition
Parenthesis, Power, Multiplication, Addition, Left to Right
What would be the output of the following code: friends = [ 'Joseph', 'Glenn', 'Sally' ] print(friends[3]) Glen Sally a blank line The program will have a runtime error.
The program will have a runtime error.
What will be displayed after the following code executes? from datetime import datetime today = datetime(2018, 4, 26) birthday = datetime(2018, 6, 21) wait_time = birthday - today days = wait_time.days print("There are", days, "days until your birthday!") There are 56 days until your birthday! There are 5 days until your birthday! There are days until your birthday! Nothing; wait_time is not a datetime object
There are 56 days until your birthday!
Give the following code what would be the output: fruit = "apple" if 'A' in fruit: print("There is an 'A' in this fruit's name.") else: print("There is no 'A' in this fruit's name.") There is an 'A' in this fruit's name. There is no 'A' in this fruit's name. A syntax error will occur. A runtime error will occur.
There is no 'A' in this fruit's name.
import numpy as np #Python Lists: a = [1, 3, 5, 7, 9] b = [2, 4, 6, 8, 10] c = a + b #NumPy Arrays: an = np.array(a) bn = np.array(b) ac = an + bn print(ac)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10] [ 3 7 11 15 19]
flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} print(flowers) flowers["blue"] = "carnation" print(flowers) print("This is a red flower:", flowers.get("red", "none")) key = "white" if key in flowers: flower = flowers[key] print("This is a", key, "flower:", flower) key = "green" if key in flowers: flower = flowers[key] del flowers[key] print(flower + " was deleted") else: print("There is no " + key + " flower") What is the last line that this code prints to the console? green was deleted lily was deleted There is no green flower There is no flower
There is no green flower
A series is a one-dimensional array which is labelled and can hold any data type.
True
Classification algorithms require a gold-standard dataset to train the model. True False
True
Hold out and cross-validation are both valid strategies for training a classification algorithm. True False
True
Independent variables are also known as features in Data Mining tasks. True False
True
Lists can be sorted but tuples cannot be sorted. True False
True
There is no "best" algorithm for classification - it is dependent on the data, tasks, and requirements of your application. True False
True
To retrieve values from a Pandas Data Frame we can reference rows and columns by name or by index value.
True
To call a function, you code the function name and a set of parentheses a set of parentheses that contains zero or more arguments a set of parentheses that contains one or more arguments a set of parentheses that contains a list of the local variables
a set of parentheses that contains zero or more arguments
To define a function, you code the def keyword and the name of the function followed by a set of square brackets a set of parentheses that contains a list of the local variables a set of parentheses that must contains one or more arguments a set of parentheses that contains zero or more arguments
a set of parentheses that contains zero or more arguments
What, if anything, is wrong with this code? rating = input("Enter the rating for this product: ") rating = rating + 2 print("The adjusted rating is " + rating + ".") nothing is wrong with this code a string variable is used in an arithmetic expression the coding in the print() function contains illegal plus signs the input() function should be an int() function
a string variable is used in an arithmetic expression
Which of the following in this expression is evaluated first? age >= 65 or age <= 18 or status == "retired" age >= 65 age <= 18 status == "retired" age >= 65 or age <= 18
age >= 65
Python comments are ignored by the compiler can be used to document what a program or portion of code does can be used so certain lines of code are not executed during testing all are true
all are true
To refer to an item in a list, you code the list name followed by an index number in brackets, starting with the number 1 an index number in parentheses, starting with the number 1 an index number in brackets, starting with the number 0 an index number in parentheses starting with the number 0
an index number in brackets, starting with the number 0
The __________ method adds an item to the end of a list. pop() append() insert() index()
append()
To determine the dimensions of a NumPy array we can use what code? arr.ndimensions() arr.dim() arr.ndimensions arr.ndim
arr.ndim
In a while loop, the Boolean expression is tested before the loop is executed after the loop is executed both before and after the loop is executed until it equals the current loop value
before the loop is executed
The following code will write what to a file? myFile = open('output.txt', 'w') line1 = "This here's the wattle,\n" myFile.write(line1) line2 = 'the emblem of our land.\n' myFile.write(line2) myFile.close() a. This here's the wattle, b. the emblem of our land. c. This here's the wattle, the emblem of our land. d. This here's the wattle, the emblem of our land.
c. This here's the wattle, the emblem of our land.
A return statement must be coded within every function can be used to allow the function to modify the value of a global variable can be used to return a local variable to the calling function can only be used once in each function
can be used to return a local variable to the calling function
To retrieve the fourth character in a string that's stored in a variable named city, you can use this code: city(3) city[3] city(4) city[4]
city[3]
To change the default colors of a matplotlib graph we use what attribute? rgbColor rgb color colors
color
To work with a file when you're using Python, you must do all but one of the following. Which one is it? open the file write data to or read data from the file decode the data in the file close the file
decode the data in the file
The following code will drop duplicate rows based on a match of all columns: data = {"Name": ["James", "Alice", "Phil", "James"], "Age": [24, 28, 40, 24], "Sex": ["Male", "Female", "Male", "Male"]} df = pd.DataFrame(data) print(df) df = df.drop_duplicates(all) df = df.drop_duplicates(axis=0) df = df.drop_duplicates() df = df.drop_duplicates(axis=1)
df = df.drop_duplicates()
The following code will drop duplicate rows based on a match of two columns and will keep the last occurrence of a duplicate: data = {"Name": ["James", "Alice", "Phil", "James"], "Age": [24, 28, 40, 24], "Sex": ["Male", "Female", "Male", "Male"]} df = pd.DataFrame(data) print(df) df = df.drop_duplicates(subset='Name', 'Age', 'first') df = df.drop_duplicates(subset=['Name', 'Age'], keep='last') df = df.drop_duplicates(subset=['Name', 'Age']) df = df.drop_duplicates(subset='Name', 'Age', keep='last')
df = df.drop_duplicates(subset=['Name', 'Age'], keep='last')
In a Pandas Data Frame we can fill in a NULL value using the value immediately above the NULL value by using what method? Before: 125 345 NULL 567 After: 125 345 125 567 df2.fillna(method='forward') df2.fillna(method='ffill') df2.fillna(method='backward') df2.fillna(method='bfill')
df2.fillna(method='ffill')
The data in __________ is persistent so it is not lost when an application ends. disk storage the application software main memory the CPU
disk storage
In the example below the Pandas Data Frame method .dropna() will... dfClean = df.dropna() drop rows that contain only NULL values drop columns that contain only NULL values drop rows with at least one NULL value drop columns that contain at least one NULL value
drop rows with at least one NULL value
What will be the result of the following code if the user enters 81 at the prompt? score_curve = 7 score = input("Enter your score on the exam: ") score_curve += score print(score_curve) 88 will be displayed on the console 81 will be displayed on the console error: you cannot use the += operator to add a string variable to an int value error: you cannot print a numeric variable
error: you cannot use the += operator to add a string variable to an int value
To retrieve the "Service" and "phd" columns of the following Pandas Data Frame we would the following code: Data Frame Name: df filteredDF = df['Service', 'phd'] filteredDF = df[['service', 'phd']] filteredDF = df[['Service', 'Phd']] filteredDF = df[('service', 'phd')]
filteredDF = df[['service', 'phd']]
To access the first three characters in a string that's stored in a variable named message, you can use this code: first_three = message[0:3] first_three = message[1:3] first_three = message.slice(0:2) first_three = message.split(0:2)
first_three = message[0:3]
The data type resulting from the following statement is print(10 / 2) integer float number string
float
Which of the following data types would you use to store the number 25.62? str int num float
float
Given the following code that creates a File Handler what method would be used to read the entire file into a single string called inputString. fhand = open('mbox-short.txt') inputString = fhand.readlines() inputString = fhand.readall() inputString = fhand.read() inputString = fhand.write()
inputString = fhand.read()
The primary difference between a tuple and a list is that a tuple has a limited range is indexed starting from 1 is mutable is immutable
is immutable
To determine the length of a string that's in a variable named city, you can use this code: len(city) city.len() length(city) city.length()
len(city)
The data in __________ is lost when an application ends. main memory the application software disk storage the CPU
main memory
To create a new empty list we can use the following code newList = list() newList = [] newList = [NULL] more than one of these answers would work
more than one of these answers would work
Which of the following will get a floating-point number from the user? my_number = input(float("Enter a number:")) my_number = float(input "Enter a number:") my_number = float(input("Enter a number:")) my_number = input("Enter a number:") float_num = my_number
my_number = float(input("Enter a number:"))
What will be displayed after the following code executes? guess = 19if guess < 19: print("Too low")elif guess > 19: print("Too high") Too low Too high nothing will display None of the answers are correct
nothing will display
To create a datetime object for the current date and time, you can use the now() method of the date class today() method of the datetime class today() method of the date class now() method of the datetime class
now() method of the datetime class
To fill a one-dimensional NumPy array of 10 elements with all zeros we can use np.zeros(0,0) np.zeros((5,2)) np.array(0) np.full(10,0)
np.full(10,0)
To create a 2-dimensional array of random numbers we could use the following code np.random.randint(0, 10, 10) np.random.randint(0, 10, (3, 3)) np.random.randint((5, 5),0, 10) samples = np.random.randint(0, 10, (10))
np.random.randint(0, 10, (3, 3))
If we have a 1-diminsional array we can convert it to a 2-dimensional array using what method? np.arange() np.range() np.shape() np.reshape()
np.reshape()
A for loop that uses a range() function is executed once for each integer in the collection returned by the range() function until the for condition is equal to the value returned by the range() function while the for condition is less than the value returned by the range() function until the range() function returns a false value
once for each integer in the collection returned by the range() function
When creating a MatPlotLib graph the last matplotlib method needs to be... plt.show() plt.plot() matplotlib.pyplot as plt plt.xticks() plt.title()
plt.show()
What methods are missing from the code below in order to create the graph shown in the image? plt.x() and plt.y() plt.labelX() and plt.ylabelY() plt.Xlabel() and plt.Ylabel() plt.xlabel() and plt.ylabel()
plt.xlabel() and plt.ylabel()
The following code would be used to reference a Row in a Pandas Data Frame by the name of the name of the Row data = np.random.normal(0, 1, (4, 4)) # mean = 0, std = 1, 3 x 3 x = ["N", "S", "E", "W"] y = ['A', 'B', 'C', 'D'] frame = pd.DataFrame(data, index=x, columns=y) print(frame.iloc["N"]) print(frame.loc["N"]) print(frame.iloc[0]) print(frame.iloc['N'])
print(frame.loc["N"])
Which function from the options given below can read a dataset from a large text file? read_file read_data read_hdf read_csv
read_csv
flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} print(flowers) flowers["blue"] = "carnation" print(flowers) print("This is a red flower:", flowers.get("red", "none")) key = "white" if key in flowers: flower = flowers[key] print("This is a", key, "flower:", flower) key = "green" if key in flowers: flower = flowers[key] del flowers[key] print(flower + " was deleted") else: print("There is no " + key + " flower") Which of the following represents a key/value pair for the dictionary named flowers defined on line 1? lily/white red/rose blue/carnation yellow/flower
red/rose
Give the following code what method would be used to replace <???> in order to find and print all lines in a file that start with the word "From:" fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if line.<???>('From:') : print(line) begins contains startswith starts
startswith
To work with dates, you need to import the date, time, and datetime classes from the datetime module the date class from the datetime module the date class from the date module the date and datetime classes from the datetime module
the date class from the datetime module
Python uses __________________ to help the programmer handle unexpected runtime errors (exceptions) . loops try / except if / elif catch / release
try / except
To keep a program from crashing (a runtime error) if an data file does not exist or if the data file is not located where we where expecting it to be located, we could use the following code Nothing is needed because python already handles this error try / except if-else We could just use the open() method.
try / except
A dictionary stores a collection of ordered items unordered items mutable items immutable items
unordered items