python test 1, Exam 2, quiz 5, exam 1, quiz 4

¡Supera tus tareas y exámenes ahora con Quizwiz!

What sort algorithms use a recursive divide and conquer approach?

-Merge Sort -Quick sort

What is the output of the following code? obj3 = pd.Series(['blue', 'purple'], index=[0, 2]) obj3 *output given* 0 blue 2 purple obj3.reindex(range(3), method='ffill') What is the output?

0 blue 1 blue 2 purple

What is the output of the following code? data2 = [[[1, 2, 3, 4], [5, 6, 7, 8]],[1,2,3]] arr2 = np.array(data2) arr2.ndim

1

What values will the following code display? (Don't worry about the order in which they will be displayed.) dct = {1:[0, 1], 2:[2, 3], 3:[4, 5]} for k,i in dct.items(): print(k,i)

1 [0, 1] 2 [2, 3] 3 [4, 5]

What is the output of the following code? arr = np.arange(-2,3) arr > 0 (arr > 0).sum()

2

What will the following code display? dct = {'Monday':1, 'Tuesday':2, 'Wednesday':3} print(dct['Tuesday'])

2

What is the output of the following code? data = { 'state': ['Ohio', 'Ohio', 'Nevada'], 'year': [2000, 2001, 2001], 'pop': [1, 2, 3] } frame2 = pd.DataFrame(data, columns=['year', 'state', 'pop'], index=['one', 'two', 'three']) (frame2.pop == frame2['pop']).sum()

3

What will be displayed after the following code is executed?def pass_it(x, y): z = x**y result = get_result(z) return(result) def get_result(number): z = number // 2 return(z) num1 = 2 num2 = 3answer = pass_it(num1, num2) print(answer)

4

What will be displayed after the following code is executed? total = 0 for count in range(4,6): total += count print(total)

4 9

What will the following code display? myset = set('1 2 3') print(len(myset))

4. Don't forget the blank space character

What is the output of the following code? data = pd.DataFrame(np.arange(9).reshape((3, 3)),index=['OH', 'CO', 'TX'],columns=['one', 'two','three']) data *output given* one two three OH 0 1 2 CO 3 4 5 TX 6 7 8 #A data.iloc[2, [2, 1, 0]] #B data.iloc[2] #C data.iloc[[1, 2], [2, 1, 0]]

A three 8 two 7 one 6 Name: TX, dtype: int32 B one 6 two 7 three 8 Name: TX, dtype: int32 C three two one CO 5 4 3 TX 8 7 6 Remembering indexes start at 0 A: third row reversed B: third row C: second, third rows reversed

obj = pd.Series(np.arange(4.), index=['a', 'b', 'c', 'd']) obj *output given* a 0.0 b 1.0 c 2.0 d 3.0 Answer each of: A B C D E #A obj['b'] #B obj[1] #C obj[2:4] #D obj[['b','d']] #E obj[[1, 3]] #F obj[obj < 2]

A 1.0 B 1.0 C c 2.0 d 3.0 D b 1.0 d 3.0 E b 1.0 d 3.0 F a 0.0 b 1.0

1. An ___________________, sometimes called an ADT, is a logical description of how we view the data and the operations that are allowed without regard to how they will be implemented. A dictionary is an example of an ADT.

Abstract data type

___________ allows us to separate l_________ and p____________ perspectives of problems. The user does not need to understand the details as long as he/she understand how to work with the interface. It helps us to reduce and manage complexity.

Abstraction logical physical

What is an algorithm?

Algorithms are how we describe the set of steps that we want the computer to do. It's the "recipe" for solving the problem at hand

When recursion is used to solve a problem, why must the recursive function call itself to solve a smaller version of the original problem?

By reducing the problem with each recursive call, the base case will eventually be reached and the recursion will stop.

In a Python class, how do you hide an attribute from code outside the class?

By starting its name with two underscore characters.

_______________ is the study of problems that are and that are not computable. It is also the study of abstraction.

Computer science

What is the output of the following slicing operation? arr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) arr3d arr3d[1, 0]

Correct output is array([7, 8, 9])

A class method does not have to have a self parameter.

False

All class definitions are stored in the library so that they can be imported into any program.

False

An object is a stand-alone program but is used by programs that need its service.

False

Index objects are mutable and can be modified by the user:

False

The elements in a dictionary are stored in ascending order, by the keys of the key-value pairs

False

numpy arrays can hold mixed type of data like standard python lists but are much faster

False - standard python lists can hold mixed types. numpy arrays can only

If you want a copy of a slice of an numpy instead of a view, you will need to explicitly copy the array—for example, arr[5:8].copy().

If you want a copy of a slice of an numpy instead of a view, you will need to explicitly copy the array—for example, arr[5:8].copy().

First n elements of list are sorted. Select next item in list and insert into sorted list. Repeat. Is what kind of sorting method?

Insertion sort

What does the get method do if the specified key is not found in the dictionary?

It returns a default value

Suppose a program uses two classes: Airplane and JumboJet. Which of these would most likely be the subclass?

JumboJet

Describe the linear search algorithm

Just go down the line, looking at each item, one at a time If we find a match, we return "True," but if we get to the end of the list and haven't found anything, return "False"

Split list in two, sort each list (recursively), merge lists; Is what kind of sorting method?

Merge sort

What would be the output of the following code? cast = {"Cardinal Ximenez" : "Michael Palin", "Cardinal Biggles" : "Terry Jones", "Cardinal Fang" : "Terry Gilliam"} cast["customer"] = "John Cleese" cast["shopkeeper"] = "Michael Palin" print(cast["shopkeeper"]) print(cast["Cardinal Ximenez"]) print(cast["Cardinal Fang"])

Michael Palin Micheal Palin Terry Gilliam

Is recursion ever required to solve a problem? What other approach can you use to solve a problem that is repetitive in nature?

No, recursion is not required. You can alternatively use a loop

What will be the output after the following code is executed and the user enters 75 and -5 at the first two prompts? def main(): try: total =int(input("Enter total cost of items")) num_items= int(input("number of items") average=total/num_items except zero_division_error: print("Error:cannot have 0 items") except Value_error print("Error: number of items cannot be negative")

Nothing; there is no print statement to display average. The ValueError will not catch the error

Given the following code fragment what is its Big-O running time? i = n while i > 0: k = 2 + 2 i = i // 2

O(log(n))

What is the average case Big-O complexity for the binary search algorithm?

O(logn); •If we have a list of size m then 2^n steps are needed to find element •n = steps = log(list size) (log₂(2ⁿ) = n)

Give the Big-O performance of the following code fragment: for i in range(n): k = 2 + 2

O(n)

What is the average case Big-O complexity for the merge sort algorithm?

O(nlogn) ; 1.Split - constant time 2.Sort sub-lists - log time (splitting list in two at each recursive call) 3.Merge - n time (vist each element exactly once)

data = pd.DataFrame(np.arange(9).reshape((3, 3)),index=['OH', 'CO', 'TX'],columns=['one', 'two','three']) data *output given* one two three OH 0 1 2 CO 3 4 5 TX 6 7 8 data.loc[:'CO', 'one']

OH 0 CO 3 Name: one, dtype: int32 Rows up to and including CO i.e. OH, CO, column 'one'

select pivot, bulid list less than pivot, and list greater than pivot, sort each of lists (recursively), concatenate low list, pivot, high list. Is what kind of sorting method?

Quick sort:

Find the min in remainder of list, swap and repeat with remainder of list. Is what kind of sorting method?

Selection sort

Describe the basic steps of the binary search algorithm

Start at some point in the middle of the list and then check if the item comes before or after. Then look in the remaining half of the list. Repeat until you find the item or it is missing

A DataFrame represents a rectangular table of data and contains an ordered collection of columns, each of which can be a different value types

True

A useful Series feature for many applications is that it automatically aligns by index label in arithmetic operations.

True

An algorithm that uses a loop will usually run faster than an equivalent recursive algorithm.

True

Assigning a column that doesn't exist to a pandas DataFrame will create a new column.

True

For arr2d, is the following statement True or False? arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) arr2d[0, 2] == arr2d[0][2]

True

If the + operator is used on strings, it produces a string that is a combination of the two strings used as its operands

True

The following operation is valid if arr is a numpy array having no zeros 1 / arr

True

A flow-chart is an example of an algorithm

True; A flow-chart is an example of an algorithm

What does the acronym UML stand for?

Unified Modeling Language

What is an overridden method?

When a subclass method has the same name as a superclass method, it is said that the method is overridden.

Why should an object's data attributes be hidden from code outside the class?

When an object's data attributes are hidden from outside code, and access to the data attributes is restricted to the object's methods, the data attributes are protected from accidental corruption. In addition, the code outside the object does not need to know about the format or internal structure of the object's data. The code only needs to interact with the object's methods. When a programmer changes the structure of an object's internal data attributes, he or she also modifies the object's methods so that they may properly operate on the data. The way in which outside code interacts with the methods, however, does not change.

What will be the value of the variable list2 after the following code executes? list1 = [1, 2, 3] list2 = [] for element in list1: list2.append(element) list1 = [4, 5, 6]

[1, 2, 3]

Which method is automatically executed when an instance of a class is created in memory?

__init__

frame = pd.DataFrame(np.arange(4).reshape((2, 2)),columns=list('ab'),index=['UT', 'OH']) frame *output given* a b UT 0 1 OH 2 3 f = lambda x: x.max() - x.min() frame.apply(f)

a 2 b 2 dtype: int64 range operation is applied by column.

When an object is passed as an argument, ________ is passed into the parameter variable.

a reference to the object

A number of very common order of magnitude functions will come up over and over as you study algorithms. These include: f(n) n n^2 2^n 1 nlog(n) n^3 log https://drive.google.com/file/d/1OvOsQwcb721Vgk4Wt9a8h7Y5WE5sEjbQ/view?usp=sharing The figure shows graphs of the above functions f(n). Label the curves shown with the most representative functions from your table above

a. 2^n - exponential b. n^3 - Cubic c. n^2 - Quadratic d. nlogn - log linear e. n - linear f. log - logarithmic g. 1 - Constant

Suppose that we have the fragment of Python code. Using assignments as your indicator of running time complexity: a. Write a formula for T(n) (running time wrt to n) for this program: _____________________ (fill in the blank) b. This program is O(___) of complexity (fill in the blank) a=5 b=6 c=10 for i in range(n): for j in range(n): x = i * i y = j * j z = i * j for k in range(n): w = a*k + 45 v = b*b d = 33

a. T(n)=3+3n**2+2n+1=3n**2+2n+4 T(n)=3+3n**2+2n+1=3n**2+2n+4. b. O(n**2)

A method that returns a value from a class's attribute but does not change it is known as a(n) ________ method.

accessor

A(n) ______________ is a step-by-step list of instructions for solving any instance of the problem that might arise.

algorithm

Which of the following can be thought of as a self-contained unit that consists of data attributes and the methods that operate on the data attributes?

an object

What is the output of arr after the following code is run? import numpy as np arr =np.arange(5) arr_slice = arr[-3:] arr_slice[0] = 123 arr

array([ 0, 1, 123, 3, 4])

what is the result of the following boolean indexing operation? names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe',]) data = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]) mask = (names == 'Bob') | (names == 'Will') data[mask]

array([[ 1, 2, 3, 4], [ 9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]])

what does the following indexing code give? arr = np.arange(12).reshape((4, 3)) arr *output given* array([ [ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) arr[[1, 3]][:, [0, 1]]

array([[ 3, 4], [ 9, 10]])

What is the output of the following code? arr = np.array([[-1,1],[-2,2],[-3,3]]) np.where(arr > 0, 2, arr)

array([[-1, 2],[-2, 2],[-3, 2]])

what is the output of the following code? arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) arr2d[2:, :]

array([[7, 8, 9]])

What is the output of the following code? arr = np.array([[1., 2., 3.], [4., 5., 6.]]) arr2 = np.array([[0., 4., 1.], [7., 2., 12.]]) arr2 > arr

array([[False, True, False],[ True, False, True]])

A recursive function .

calls itself

Write a class definition named Car. The Car class should have data a attribute for a Car's make. The class should also have the following: a. An __init__ method for the class. The method should accept an argument for each of the data attributes. b. Accessor and mutator methods for each data attribute. c. __str__ method that returns a string indicating the state of the object

class Car: # Initializer def __init__(self, make): self.__make = make # Mutators def set_make(self, make): self.__make = make # Accessors def get_make(self): return self.__make # __str__ method def __str__(self): state_string = ('make: ' + self.__make + '\n') return state_string

Look at the following class definition: class Beverage: def _ _init_ _(self, bev_name): self._ _bev_name = bev_name Write the code for a class named Cola that is a subclass of the Beverage class. The Cola class's __init__ method should call the Beverage class's __init__ method, passing 'cola' as an argument.

class Cola(Beverage): def init (self): Beverage. init (self, 'cola')

What is the output of the following code? data = pd.DataFrame(np.arange(6).reshape((3, 2)),index=['OH', 'CO', 'TX'],columns=['one', 'two']) data *output given* one two OH 0 1 CO 2 3 TX 4 5 data[data['one'] > 2] What is the output?

data[false,false,true] would select all of the last row

What is the name of the pandas method that produces multiple summary statistics for numeric data (count, mean, std, min, 25%,50%,75%,max) in one shot?

describe()

if frame is a pandas dataframe, what pandas methods show you the first 5 and last 5 rows of a data frame?

frame.head() frame.tail()

Assume the variable dct references a dictionary. Write an if statement that determines whether the key 'James' exists in the dictionary. If so, display the value that is associated with that key. If the key is not in the dictionary, display a message indicating so.

if 'James' in dct: print(dct['James']) else: print('James is not in the dictionary.')

Assume the variable dct references a dictionary. Write code that pickles the dictionary and saves it to a file named mydata.dat.

import pickle output_file = open('mydata.dat', 'wb') # write out in binary pickle.dump(dct, output_file) output_file.close()

In order to avoid KeyError exceptions, you can check whether a key is in the dictionary using the ________ operator

in

The ________ operator can be used to determine whether one string is contained in another string.

in

When function A calls function B, which calls function A, it is called recursion.

indirect

The ________ built-in function is used to read a number that has been typed on the keyboard.

input()

Each object that is created from a class is called a(n) ________ of the class.

instance

Suppose my_car is the name of a variable that references an object, and go is the name of a method. Write a statement that uses the my_car variable to call the go method. (You do not have to pass any arguments to the go method.)

my_car.go()

Write a statement that creates a dictionary containing the following key-value pairs: 'a' : 1 'b' : 2 'c' : 3

mydict = {'a':1, 'b':2, 'c':3}

Which method would you use to get the value associated with a specific key and remove that key-value pair from the dictionary?

pop

The ________ method returns a randomly selected key-value pair from a dictionary in versions of Python earlier than 3.7.

popitem()

Look at the following code: set1 = set([100, 200, 300, 400, 500]) set2 = set([200, 400, 500]) Which of the sets is a superset of the other?

set1 is a superset of set2

Assume each of the variables set1 and set2 references a set. Write code that creates another set containing the elements that appear in set1 but not in set2, and assigns the resulting set to the variable set3.

set3 = set1.difference(set2)

The ________ method returns the list of the words in a string.

split()

What is the equivalent list comprehension for the following ?: sq_list = [] for x in range(1, 11): if x % 2 == 0: sq_list.append(x * x)

sq_list = [x*x for x in range(1,11) if x%2 == 0 ]

What is the equivalent list comprehension for the following ?: sq_list = [] for x in range(1, 11): if x % 2 == 0: sq_list.append(x * x)

sq_list = [x*x for x in range(1,11) if x%2 == 0 ]

A subclass can have a method with the same name as a method in the superclass.

true

Object reusability has been a factor in the increased use of object-oriented programming

true

Polymorphism allows you to write methods in a subclass that have the same name as methods in the superclass.

true

You cannot directly call the _ _str_ _ method.

true

data = pd.DataFrame(np.arange(9).reshape((3, 3)),index=['OH', 'CO', 'TX'],columns=['one', 'two','three']) data *output given* one two three OH 0 1 2 CO 3 4 5 TX 6 7 8 data.loc['CO', ['two', 'three']] What is the output?

two 4 three 5 Name: CO, dtype: int32

names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe']) np.______(names) array(['Bob', 'Joe', 'Will'], dtype='U4')

unique

What will be displayed after the following code executes? (Note: the order of the display of entries in a dictionary are not in a specific order.) cities = {'GA' : 'Atlanta', 'NY' : 'Albany', 'CA' : 'San Diego'} if 'CA' in cities: del cities['CA'] cities['CA'] = 'Sacramento' print(cities)

{'CA': 'Sacramento', 'NY': 'Albany', 'GA': 'Atlanta'}

After the following statement executes, what elements will be stored in the myset set? myset = set(['a', 'bb', 'ccc', 'dddd'])

{'a', 'bb', 'ccc', 'dddd'}

What would be the output of the following code? primes = {3, 5, 7, 11, 13, 17, 19, 23, 29} teens = set([13, 14, 15, 16, 17, 18, 19]) print(primes - teens)

{3, 5, 7, 11, 23, 29}

You can use __________ to create an empty dictionary.

{}


Conjuntos de estudio relacionados

WGU COM101 Exam Two Chapters 5-7

View Set

1.0 Most organisms are active in a limited temperature range

View Set

Chapter 9: Production & Operations Management

View Set

Chapter 66: Care of Patients with Urinary Problems

View Set

Management Final Practice Questions

View Set

Chapter 5 - Innovation: The Creative Pursuit of Idea

View Set

MIS FINAL EXAM WARM UP AND QUIZZES

View Set