Python Final Review

Ace your homework & exams now with Quizwiz!

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

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

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

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

What is the value stored in "my_var" after the following code is executed? my_var = [1,2,3][1]

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

class A: def __init__(self): self.multiply(15) self(self.i) def multiply(self, i): self.i = 4 * i class B(A): def __init__(self): super().__init__() def multiply(self, i): self.i = 2 * i obj = 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">

Package

A collection of modules that share a namespace

How should software be tested?

A combination of both

Which of the following can be used to make a DataFrame?

A different DataFrame A Series A structued ndarray Correct! All of the above

Which of the following statements is true?

A non-private method in a superclass can be overridden

Given the code below, what datatype is B? B = np.mat([ [5,6], [5,6] ])

A numpy matrix

Which of the following can be used to create a DataFrame in pandas?

A scalar value An ndarray A python dictionary Correct! All of the above

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

Which statement best describes polymorphism?

A way to permit objects of different types and behaviors to be treated as the same general type

An accessor method is used to:

Access values internal to a class from outside.

Object

An instance of a class

The following numpy command performs what function? np.full((3,3), True, dtype=bool)

Creates a 3x3 numpy array of all Trues

Which of the following operations in pandas works with a syntax the same as that of the analogous dictionary operations?

Deleting columns Setting columns Getting columns Correct! All of the above

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

"1" + "1" = "2"

False

A Panel is generally a 2D array which is labelled and also size-mutable.

False

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 is the purpose of using div tags in HTML?

For creating different sections

"Hello world".upper()[0:5]

HELLO

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

NameError

Python tried to use a variable/function that hasn't been defined

SyntaxError

The Python interpreter wasn't able to understand a line of code

Histograms are best used for showing:

The distribution of a list of numbers

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 URL is easily stored as a string.

True

A class can have more than one child.

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

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

Composition enables Python to create a complex type by combining types of other objects.

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 joblib tool in SciKit-Learn allows you to save and load trained models for future use.

True

The program below will NOT loop forever. count = 0 while count > 0: count = count + 1 print(count)

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

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

When you are done creating a Notebook, you can share it as Python code, as HTML, and in several other useful formats.

True

You must import the json module before you can use the load function.

True

UML is an abbreviation of:

Unified Modeling Language

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__()

The constructor is always called:

__init__()

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] Which of the following functions will you use?

a.extend(b)

Which of the following demonstrates proper syntax for accessing a dictionary's value?

a_dictionary["Key"]

This numpy command will create a 1D array of numbers from 0 to 9.

arr = np.arange(10)

What function in BeautifulSoup will remove a tag from the HTML tree and destroy it?

decompose()

How would you define a function named openDoor? Assume it takes no arguments.

def openDoor():

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)

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 = name self.age = age class JackRussellTerrier(Dog): pass class Dachshund(Dog): pass class Bulldog(Dog): pass miles = 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 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 of the following code snippets are equivalent?

squared = [] for value in values: squared.append(value**2) squared = [value**2 for value in values]

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

Which of the following statements is most accurate for the declaration x = Circle()?

x contains a reference to a Circle object

Which of the following values evaluate to True under Python's truthiness rules?

134432 1 > 5 or 3

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

How many values can each of these operators take? < 2 not 1 and 2 != 2

2 1 2 2

(10 + 8) % 12

6

Module

A file that contains 0-n classes

What type of thing is returned from the function below? def is_on_fire(): return True

Boolean

Dictionaries are useful because you can have duplicate keys.

False

Dictionaries will always have at least one key and one value.

False

Dictionary keys are always strings.

False

Every function must return an integer or a string.

False

Every if statement must be followed by either an else or an elif.

False

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 always returns a string.

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

Library

Functional structure that is used for general-purpose access from other programs

In the following code, the print statement is ________ the if statement. if conditional: print("The conditional was true")

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

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

Faults found by users are due to:

Poor software and poor testing

KeyError

Python couldn't find a key in a dictionary

IndexError

Python couldn't find a valid location in a list

TypeError

Python tried to apply an operation/function to an inappropriate type

The super() method performs what function?

Returns a temporary object of the parent class

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

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

ValueError

The value passed to a function is of an incorrect type

A class can have more than one parent.

True

A class in Python is defined with the keyword class.

True

A state represents the current values of all instance data internal to the object.

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

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 elif is equivalent to an else with an if statement nested inside it.

True

The input() function always returns a string.

True

The program below will NOT loop forever. count = 10 while count >= 0: count = count - 1 print(count)

True

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. Correct!

True

When should you stop testing?

When stated test completion criteria have been met

Software testing activities should start:

as soon as possible in the development life cycle

All modules are packages, but not all packages are modules.

False

All Python programs must have a main() function to control the execution of other functions.

False

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 Correct! "" in title Correct! "Dog" == "Dog" Correct! "Alabama" < "Virginia"

Class

"Blueprint" that defines an object

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

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

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)

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

A while loop will always execute at least once.

False

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()

Given this program: name = input("What is your name?") def fix_capitalization(name): return name.title().strip() def print_message(name): print("Hello", name, "how are you?") which of the following lines of code will have the data flow correctly through both functions in order to print the message with the fixed capitalization?

print_message(fix_capitalization(name)) name = fix_capitalization(name) print_message(name)


Related study sets

Eliopoulos - Gerontological Nursing 8th Ed - The Aging Population CH 1, Eliopoulos - Gerontological Nursing 8th Ed - Diversity CH 3, Eliopoulos - Gerontological Nursing 8th Ed - Theories of Aging CH 2, Eliopoulos - Gerontological Nursing 8th Ed - Com...

View Set

ALTA - CHAPTER 5 - CONTINUOUS RANDOM VARIABLES

View Set

Differences in Environmental Influences: Diathesis Stress & Differential Susceptibility

View Set