S364 Midterm
To concatenate two string variables you can use what symbols/characters?
+
Valid functions and methods used with sets include the following except
.insert()
To order a list into an alphabetical order or sequential order we can use what method?
.sort()
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]])
2-dimensional
How many items does the following dictionary contain? flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"}
3
What is the value of my_num after the following statement executes? my_num = (50 + 2 * 10 - 4) / 2
33
The code below creates a set with _____ values/items. set_2 = {1, 2, 3, 4, 4}
4
Given: x = 23 , y = 15 What is the value of new_num after the following statement executes? new_num = x % y
8
What will be displayed after the following code executes? book_name = "a tale for the knight"book = book_name.title()print(book)
A Table For The Knight
Which among the following options can be used to create a Data Frame in Pandas?
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")
An error would occur with this code
To change the default colors of a matplotlib graph we use what attribute?
Color
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.
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])
False
The .info() method of the Pandas Data Frame will provide the number of NULL values found in each column of data.
False
The following code creates a NumPy list of integers. import numpy as np arr_a = np.array([1, 2, 0.0])
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 line of code will fill in NULL values with the mean of the entire column. df5 = df2.fillna(df.average(), inplace=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?
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)
False True
One of many popular editors for Python that will be used in class is called ________________.
Jupyter
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]])
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)
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.)
Number
The correct order of operation in programming (a.k.a. Precedence Rules) is the following:
Parenthesis, Power, Multiplication, Addition, Left to Right
What will be displayed after the following code executes? from datetime import datetimetoday = datetime(2018, 4, 26)birthday = datetime(2018, 6, 21)wait_time = birthday - todaydays = wait_time.daysprint("There are", days, "days until your birthday!")
There are 56 days until your birthday!
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?
There is no green flower
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()
This here's the wattle, the emblem of our land.
A series is a one-dimensional array which is labelled and can hold any data type.
True
Lists can be sorted but tuples cannot be sorted.
True
To retrieve values from a Pandas Data Frame we can reference rows and columns by name or by index value.
True
The following code would cause an run-time error (would not work). a = np.array([1, 3, 5])b = np.array([6])
True / False
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 + bnprint(ac)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10] [ 3 7 11 15 19]
Each item in a dictionary is
a key/value pair
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 + ".")
a string variable is used in an arithmetic expression
To refer to an item in a list, you code the list name followed by
an index number in brackets, starting with the number 0
The __________ method adds an item to the end of a list.
append()
To determine the dimensions of a NumPy array we can use what code?
arr.ndim
Python is considered a good first language to learn because: a. powerful for all-purpose programming b. it has a simple syntax c. all of the choices are true d. programs can be written quickly
c. all of the choices are true
To retrieve the fourth character in a string that's stored in a variable named city, you can use this code:
city[3]
Python comments: a. are ignored by the compiler b. can be used to document what a program or portion of code does c. can be used so certain lines of code are not executed during testing d. all are true
d. all are true
To create a new empty list we can use the following code a. newList = list() b. newList = [] c. newList = [NULL] d. more than one of these answers would work
d. more than one answer would work
To work with a file when you're using Python, you must do all but one of the following. Which one is it?
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()
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'], 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 345NULL 567 After: 125 345125 567
df2.fillna(method='ffill')
The data in __________ is persistent so it is not lost when an application ends
disk storage
In the example below the Pandas Data Frame method .dropna() will... dfClean = df.dropna()
drop rows with at least one NULL value
All of the following are true of a Python Set except:
elements cannot be of different data types
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)
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 rank discipline phd service sex salary 0 Prof B 56 49 Male 186960 1 Prof A 12 6 Male 93000 2 Prof A 23 20 Male 110515 3 Prof A 40 31 Male 131205 4 Prof B 20 18 Male 104800 .. ... ... ... ... ... ...
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]
The data type resulting from the following statement is print(10 / 2)
float
Which of the following data types would you use to store the number 25.62?
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.read()
The primary difference between a tuple and a list is that a tuple
is immutable
To determine the length of a string that's in a variable named city, you can use this code:
len(city)
The data in __________ is persistent so it is not lost when an application ends
main memory
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
more than one of the print statements will work
To print the first 5 rows of the following Pandas Data Frame we use df = pd.read_csv("Salaries.csv")
more than one option would work
Which of the following will get a floating-point number from the user?
my_number = float(input("Enter a number:"))
To create a datetime object for the current date and time, you can use the
now() method of the datetime class
To create a 2-dimensional array of random numbers we could use the following code
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.reshape()
To fill a one-dimensional NumPy array of 10 elements with all zeros we can use
np.zeros(0,0) or np.full(10,0)
What method is used to create a matplotlib Bar Chart?
plt.bar()
When creating a MatPlotLib graph the last matplotlib method needs to be...
plt.show()
What methods are missing from the code below in order to create the graph shown in the image? import pandas as pdimport matplotlib.pyplot as plt df = pd.read_csv("sales_data.csv")monthList = df ['month_number'].tolist()toothPasteSalesData = df ['toothpaste'].tolist()plt.scatter(monthList, toothPasteSalesData, label = 'Tooth paste Sales data')plt.legend(loc='upper left')plt.title(' Tooth paste Sales data')plt.xticks(monthList)plt.grid(True, linewidth= 1, linestyle="--")plt.show()
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.loc["N"])
Which function from the options given below can read a dataset from a large text file?
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?
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)
startswith
To create a datetime object by parsing a string, you can use the
strptime() method of the datetime class
To work with dates, you need to import
the date class from the datetime module
What would be the output of the following code: friends = [ 'Joseph', 'Glenn', 'Sally' ]print(friends[3])
the program will have a runtime error
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
try / except
A dictionary stores a collection of
unordered items