Python Final
What is printed after the code below is executed? def change_value(a_variable): *a_variable = 5 *return a_variable a = 0 change_value(a) print(a)
0
UML is an abbreviation of:
Unified Modeling Language
What will be the output of the following code snippet: class Sales: *def __init__(self, id): **self.id = id **id = 100 val = Sales(123) print(val.id)
123
Which of the following statements is most accurate for the declaration x = Circle()?
x contains a reference to a Circle object
A Panel is generally a 2D array which is labelled and also size-mutable.
False
A while loop will always execute at least once.
False
The print() function always returns a string.
False
What is the purpose of using div tags in HTML?
For creating different sections
The return statement is used to send a value out of a function.
True
Values enter functions as arguments when the function is called, and then the arguments' values are assigned to parameters when the function's body begins executing.
True
You must import the json module before you can use the load function.
True
This numpy command will create a 1D array of numbers from 0 to 9.
arr = np.arange(10)
Software testing activities should start:
as soon as possible in the development life cycle
Which of the following creates a section header in Markdown?
# Introduction
How many graphs will the following code create? import matplotlib.pyploy as plt plt.hist([1,2,3]) plt.hist([1,2,3]) plt.show()
1
What will be the output of the following code: class A:def __str___(self):return '1'class B(A):def __init__(self):super().__init__()class C(A):def __init__self():super().__init__()def main():obj1 = B()obj2 = A()obj3 = C()print(obj1, obj2, obj3)main()
1 1 1
Imagine that you are working on a project which is a binary classification problem. You tried a model on a training dataset and get the confusion matrix below on the testing dataset: n = 165Predicted NOPredicted YESActual NO5010Actual YES5100 Based on the above confusion matrix, choose which option(s) below are correct statements. 1. Accuracy is ~0.91 2. Misclassification rate is ~0.91 3. False positive rate is ~0.95 4. True positive rate is ~0.95
1 and 4
Which of the following options is/are true for k-fold cross-validation? 1. Increasing k will result in more time required to cross-validate the results. 2. Higher values of k will result in higher confidence on the cross-validation results. 3. If k=N, then it is called "Leave One Out Cross-Validation," where N is the number of data points.
1, 2, and 3
The function add5() below returns the number 5 added to the argument. What value will the variable 'x' hold after the line is executed? x = add5(10) * add5(2)
105
After the third iteration of the loop, what is the value of sum? sum = 0 values = [4,2,6] for value in values: *sum = sum + value
12
How many branches does this code have? if conditional: *print(5) else: *print(2)
2
How many branches does this code have? if conditional: *print(5) print(2)
2
How many elements will the result of this list comprehension have? old = [1,2,3] new = [old*2 for i in old if i > 1]
2
What will be the output of the following code: class Demo:def __init__(self):self.x = 1def change(self):self.x = 10class Demo_derived(Demo):def change(self):self.x = self.x + 1return self.xdef main():obj = Demo_derived()print(obj.change())main()
2
How many values can each of these operators take? < 2 not 1 and 2 != 2
2 1 2 2
How many branches does this code have? if conditional: *if second_conditional: **print(5) *print(1) print(2)
3
How many elements will the result of this list comprehension have? old[1,2,3] new = [old*2 for i in old]
3
What will be printed after this code is run? points = {"Virginia Tech": 5} points["Virginia Tech"] = 3 print(points["Virginia Tech"])
3
What will be the output of the following code: class A:def __init__(self):self.multiply(15)self(self.i)def multiply(self, i):self.i = 4 * iclass B(A):def __init__(self):super().__init__()def multiply(self, i)self.i = 2 * iobj = B()
30
Which of the following tags is the correct way to create a hyperlink?
<a href="http://www.website.com">http://www.website.com</a>
Which of the following tags create bolded text in HTML?
<b> <strong>
Which of the following tags create italicized text in HTML?
<i> <em>
Which of the following tags creates a checkbox?
<input type="checkbox">
Which of the following statements is true?
A non-private method in a superclass can be overridden
Which of the following are hazards of using web data?
A slow Internet connection Losing your Internet connection The website changing the file without telling you Too many students visiting the same website for an assignment and causing it to crash The website changing the file's format without telling you
An accessor method is used to:
Access values internal to a class from outside.
Which of the following can be used to create a DataFrame in pandas?
All of the above
Which of the following can be used to make a DataFrame?
All of the above
Which of the following operations in pandas works with a syntax the same as that of the analogous dictionary operations?
All of the above
Match the term to its description Object Class Module Package Library
An instance of a class "Blueprint" that defines an object A file that contains 0-n classes A collection of module that share a namespace Functional structure that is used for general-purpose access from other programs
The following numpy command performs what function? np.full((3,3), True, dtype=bool)
Creates a 3x3 numpy array of all Trues
What will be the output of the following code: class Demo:def __check(self):return "Demo's check "def display(self):print(self.check())class Demo_derived(Demo):def __check(self):print "Derived's check "Demo().display()Demo_derived().display()
Demo's check Demo's check
If 10 floating-point values are stored in an ndarray A, what is the result of the operation A*10?
Each item in the array is multiplied by 10
The definition "a machine learning approach that combines the results from many different algorithms, whose combined vote provides a more robust and accurate predictive output than any single algorithm" refers to:
Ensemble Learning
A Series is a one-dimensional array which is labelled and can only store primitive data types (int, float, bool, str).
False
After the following code is executed to retrieve a JSON file: import requests response = requests.get("www.example.com/data.json") You can print a JSON representation of the website with the following code: print(response.json)
False
Bar graphs and histograms are the same thing.
False
Classification problems try to map input variables to some continuous function, while regression problems try to map input variables into discrete categories.
False
Data Science is a straightforward process with no iterative design.
False
Data Science is another name for Computer Science.
False
Markdown is a type of Python code.
False
Matplotlib is the only way to create visualizations in Python.
False
Notebooks are a basic part of a Python installation.
False
Notebooks are a useful file format for sharing data, like JSON or CSV.
False
Notebooks are strictly a tool for educational purposes.
False
Overriding means changing behavior of methods of derived class methods in the base class.
False
Sorting and ranking a DataFrame are the same operation.
False
The get function from the requests module consumes a string URL and returns a string representing the contents of the website.
False
The load method from the json module consumes a string representing a filename.
False
Unsupervised learning algorithms are impossible because a computer cannot learn classifications without training data.
False
The process for training a classifier on training data is called:
Fitting
What are the advantages of numpy arrays over classic Python lists?
Insertion, concatenation, and deletion are faster It has better support for mathematical operations They consume less memory Correct! All of the above
What is the function of a tag in HTML?
It indicates some behavior that your web browser uses for formatting
What is the benefit of "duck typing?"
Less restriction on the type values that can be passed to a method
Give the file scores.json with the following contents: [44, 45, 23, 33] And the following code: import json scores = json.load(open('scores.json')) What is the type of scores?
List of Integer
Which component of a TensorFlow learning process should be minimized during optimization?
Loss function
How many times do you need to import Matplotlib?
Once, at the start of the program
Which of the following is an example of a deterministic algorithm?
PCA
The process for testing a classifier on the validation dataset is called:
Predicting
Which is these is the biggest reason for incorporate polymorphism into a software system?
The program will have a more elegant design and will be easier to maintain and update
Scatter Plots are best used for showing:
The relationship between two lists of numbers
Line Plots are best used for showing:
The trend in a list of numbers
"Active Learning" refers to learning algorithms that can interactively query the user to obtain new information.
True
A "testing dataset" and a "validation dataset" are interchangable terms for the same concept.
True
A DataFrame is similar to a fixed-size dictionary because you can use the index labels to get and set values.
True
A Notebook is composed of Markdown, Code, and the results of running that Code.
True
A class in which one or more methods are only implemented to raise an exception is called an abstract class.
True
A pandas Series acts in a way similar to that of an array.
True
A state represents the current values of all instance data internal to the object.
True
After the following code is executed to retrieve a text file: import requests response = requests.get("www.example.com/data.txt") You can print the text of the website with the following code: print(response.text)
True
All elements within an ndarray must have the same type.
True
Data Science involves extracting meaning from data.
True
Discriminative models learn to discriminate between inputs (e.g., the picture contains a dog vs. the picture contains a cat).
True
If data is provided in the form of an ndarray, the index and the data MUST be of the same length.
True
In TensorFlow Keras, you assemble layers to build models.
True
The SciKit-Learn k-Nearest Neighbors classifier allows a programmer to select the number of neighbors to include when determining a classification.
True
The TensorFlow Model.evaluate() method computes the performance of the model.
True
The input() function always returns a string
True
The joblib tool in SciKit-Learn allows you to save and load trained models for future use.
True
The standard marker for missing data in pandas is NaN.
True
To make a plot appear in Matplotlib, the show() function is necessary.
True
Tuples are immutable -- they cannot be changed after being created.
True
When you are done creating a Notebook, you can share it as Python code, as HTML, and in several other useful formats.
True
Which of the following describe Supervised Learning:
Uses a training dataset and a testing dataset Mostly regression and classification problems Identifying a relationship between input and output
Which of the following commands will extract all odd numbers from an array arr that contains the numbers 0-9?
_ = arr[arr % 2 == 1] arr = arr[arr % 2 == 1]
Which instance variable can tell you the name of any superclass?
__bases__
Which of the below are magic ("dunder") methods that are defined for every Python object?
__getitem__() __add__() __str__() __eq__() __ne__() __lt__() __le__() __gt__() __ge__(
Assume that you are given two lists: a = [1,2,3] b = [4,5,6] Your task is to create a single list which contains the elements of a and b in a single dimension: a = [1,2,3,4,5,6]
a.extend(b)
What type of thing is returned from the function below? def is_on_fire(): *return True
boolean
What function in BeautifulSoup will remove a tag from the HTML tree and destroy it?
decompose()
This pandas command will replace missing values in a DataFrame with the provided parameter.
fillna()
The overarching goal of software testing is to:
find whether the software works incorrectly
What function in BeautifulSoup allows you to retrieve all instances of an HTML tag?
find_all()
What function in BeautifulSoup allows you to retrieve the value associated with an HTML attribute?
get()
Which of the following two snippets of code are equivalent and correct?
import json file = open("scores.txt") json.load(file) from json import load file = open("scores.txt") load(file)
Given two input arrays a and b, what function in numpy will return an array containing the items common to a and b?
intersect1d(a,b)
Which HTML attribute allows you to give a name to a section of text?
name
Which command in numpy will generate five random numbers from the normal distribution?
np.random.normal(size = 5)
Which function in numpy will convert a 1D array into a 2D array?
reshape()
Which property of an ndarray in numpy will tell you the number of rows and columns?
shape
Which HTML attribute allows you to apply a CSS style to a section of text?
style class id
The best definition of software testing is:
technical investigation done to expose quality-related information about the product under test
Which of these is an invalid writer function in pandas?
to_text()
The SciKit-Learn function to split a dataset into testing and training components is:
train_test_split()
Data structures in pandas can be mutated in terms of ___________ but not of ______________.
value, size
When should you stop testing?
when the test completion criteria have been met
"1" + "1" = "2"
False
Given the code below, what datatype is B? B = np.mat([ [5,6], [5,6] ])
A numpy matrix
Which statement best describes polymorphism?
A way to permit objects of different types and behaviors to be treated as the same general type
The correct way to instantiate the following class is: class Dog: *def __init__(self, name, age): **self.name = name **self.age = age
Dog("Rufus", 3)
Histograms are best used for showing:
The distribution of a list of numbers
A URL is easily stored as a string.
True
Which of the following values evaluate to True under Python's truthiness rules?
134432 1 > 5 or 3
What is the value stored in "my_var" after the following code is executed? my_var = [1,2,3][1]
2
Predict the result of this expression: (10 + 8) % 12
6
Type the character used at the end of the first line of a for loop.
:
How should software be tested?
A combination of both manually and automation
Dictionaries are useful because you can have duplicate keys.
False
Dictionaries will always have at least one key and one value.
False
Predict the result of this expression: "Hello world".upper()[0:5]
HELLO
In the following code, the print statement is ________ the if statement. if conditional: *print("The conditional was true")
Inside
Faults found by users are due to:
Poor software and poor testing
Match each error type to the correct explanation. NameError TypeError SyntaxError IndexError KeyError ValueError
Python tried to use a variable/function that hasn't been defined Python tried to apply an operation/function to an inappropriate type The Python interpreter wasn't able to understand the line of code Python couldn't find a valid location in a list Python couldn't find a key in a dictionary The value of a function is of an incorrect type
The super() method performs what function?
Returns a temporary object of the parent class
What is the type of the Iteration Variable in this code? groceries = ["Apples", "Cookies", "Steaks"] for grocery in groceries: *print(grocery)
String
What will be the output of the following code snippet? class A:def __init__(self):self.calcI(30)print("i from A is", self.i)def calcI(self, i):self.i = 2 * iclass B(A):def __init__(self)super().__init__()def calcI(self, i):self.i = 3 * ib = B()
The __init__ method of class A gets invoked and it displays "i from A is 90"
What does the __dict__ instance variable provide?
The methods provided by the class
A UML Class Diagram contains the following:
The name of the class Variables stored within the class Functions that modify attributes of the class
Information hiding is a convention for hiding changes internal to an object from the user.
True
Lists and strings are both sequences of data.
True
Methods are functions that are internal to a class.
True
The constructor is always called:
__init__()
Which of the following demonstrates proper syntax for accessing a dictionary's value?
a_dictionary["Key"]
How would you define a function named openDoor? Assume it takes no arguments.
def openDoor():
Identify the type of each literal value. 5 False 5.0 None "None" 4.3 "True" -7
integer boolean float None String Float string integer
Select each of the expressions that evaluate to True according to the rules of Truthiness in Python.
" " "1 > 5" -12345 "False" "Professor"[1:3] 1 > 5 or 3
Mark each of the following expressions if they evaluate to True. Assume that the following code is executed first: title = "Harry Potter"
" " in title "" in title "Dog" == "Dog" "Alabama" < "Virginia"
What is the output of the following code: class Dog:def walk(self):return "*walking*"def speak(self):return "Woof!"class JackRussellTerrier(Dog):def speak(self):return "Arf!"bobo = JackRussellTerrier()bobo.walk()
*walking*
Keys cannot be added to a dictionary after the dictionary has been created.
False
Methods always change the internal state of a mutable object.
False
The print() function is necessary to call a function.
False
The program below will NOT loop forever. count = -5 while count < 0: *count = count - 1 print(count)
False
The return statement is used to send a variable out of a function.
False
Tuples are composed of key/value pairs.
False
When creating a new object, the constructor is directly called by name.
False
You can use the append method to add elements to tuples.
False
Which of the following values evaluate to False under Python's truthiness rules?
False None 0.0 0/7 "" 0
What is the subtype of the following literal value? [4.5, 3.2, 7.3]
Float
What is the output of the following code? class Dog:def walk(self):return "*walking*"def speak(self):return "Woof!"class JackRussellTerrier(Dog):def speak(self):return "Arf!"bobo = JackRussellTerrier()bobo.speak()
Arf!
Dictionary keys are always strings.
False
Which of the following statements are correct about the given code snippet? class A: *def __init__(self, i=0): **self.i = i class B(A): *def __init__(self, j=0): **self.j = j def main(): *b = B() *print(b.i) *print(b.j) main()
Class B inherits A, but the data field "I" in A is not inherited
UML diagrams include:
Class diagrams Sequence diagrams State diagrams Component diagrams Object diagrams Activity diagrams Timing diagrams Use case diagrams Package diagrams Deployment diagrams
Every function must return an integer or a string.
False
Every if statement must be followed by either an else or an elif.
False
Which of these statements are true?
Each object is an instance of a class. A method describes what an object can do. Everything in Python is an object. Assigning a value to a variable is the same operation as binding a name to an object. The self parameter is an object's way to refer to itself. A constructor is a method that creates an object.
A namespace prevents multiple instances of the same class from being created.
False
All Python programs must have a main() function to control the execution of other functions.
False
All modules are packages, but not all packages are modules.
False
Is the print call before, inside, or after the for loop? for name in names: *print(name)
Inside
What is the type of the following list value? [4.5, 3.2, 7.3]
List
What is the type of the result of the following expression? "1,2,3,4".split(",")
List
Which loop pattern does this code most resemble? lowest = 100 grades = [90,64,72,50] for grade in grades: *if lowest > grade: **lowest = grade print(lowest)
Max/Min
A mutator method is used to:
Modify values internal to a class from outside.
What is the value of number_of_users after this program executes? if False: *number_of_users = 5 print(number_of_users)
No value, because an error occures since the value has not been defined
What will be the output of the following code snippet? class A:def __init__(self):self.calcI(30)def calcI(self, i):self.i = 2 * iclass B(A):def __init__(self):super().__init__()print("i from B is", self.i)def calcI(self, i):self.i = 3 * ib = B()
The __init__ method of class A gets involed and it displays "i from B is 90"
Mark each of the following statements about for loops that are true:
The iteration variable will take on each value of the list variable, one at a time. Like an if statement and a function call, the for loop might cause the execution to not follow the order of the code lines
A class can have more than one child.
True
A class can have more than one parent.
True
A class in Python is defined with the keyword class.
True
Composition enables Python to create a complex type by combining types of other objects.
True
Encapsulation is a design principle of OOP stating that only the methods of a class should be able to change the values of the instance variables.
True
The elif is equivalent to an else with an if statement nested inside it.
True
The program below will NOT loop forever. count = 0 while count > 0: *count = count + 1 print(count)
True
The program below will NOT loop forever. count = 10 while count >= 0: *count = count - 1 print(count)
True
What is the value of "any" after the following code is executed: conditions = [False, False, True, False] any = False for condition in conditions: *any = any or condition print(any)
True
What is the value stored in "my_var" after the following code is executed? my_var = 5 in [1,3,5]
True
Given the following code snippet, which of the following pairs of statements and outputs are correct? class Dog:def __init__(self, name, age):self.name = nameself.age = ageclass JackRussellTerrier(Dog):passclass Dachshund(Dog):passclass Bulldog(Dog):passmiles = JackRussellTerrier("Miles", 4)buddy = Dachshund("Buddy", 9)jack = Bulldog("Jack", 3)jim = BullDof("Jim", 5)
isinstance(jack, Dachshund)False isinstance(miles, Bulldog)False isinstance(buddy, Bulldog)True isinstance(miles, Dog)True
Which of the following statements can be used to check whether an object obj is an instance of class A or not?
isinstance(obj, A)
How would you call a function named openDoor? Assume it takes no arguments.
openDoor()
name = input("What is your name?") def fix_capitalization(name): *return name.title().strip() def print_message(name): *print("Hello", name, "how are you?"
print_message(fix_capitalization(name)) name = fix_capitalization(name) print_message(name)
Which of the following code snippets are equivalent?
squared = [] for value in values: *squared.append(value**2) squared = [value**2 for value in values]