CS 2

Ace your homework & exams now with Quizwiz!

Which of the following is not a correct pairing of a file access mode to its string?

'rw' - read/write access.

Three types of indexing in Numpy

- Field access: using the index of the value - Basic Slicing: using the start, stop, and step parameters to the built in slice function - Advanced indexing

Dangers of adding two arrays

- arrays must be dense, no holes - must be one type - cannot combine arrays of different shape

Numpy features

- typed multidimentional arrays (matrices) - fast numerical computations (matrix math) - high level math functions

Given the string: greeting = "hello there!", what index is returned when we call greeting.find("he")?

0

Rules for numpy broadcasting Broacasting occurs if one of the follwing is satisfied:

1. The smaller dimension ndarray can be appended with '1' in its shape. 2. the size of each output dimension should be the maximum of the input sizes in the dimension 3. it is important to note that input can be used in the calculation only if its size in a particular dimension matches the output size or its value is exactly 1 4. Suppose the input size is 1, then the first data entry should be used for the calculation along the dimension

Shaping a = np.array([1,2,3,4,5,6]) a = a.reshape(3,2_ a = a.reshape(2,-1) a = a.ravel()

1. total number of elements cannot change 2. if you want numpy to auto determine size length should be sepcify the dimension as -1 3. if no parameter is passed, the the ravel function will flatten/ravel 2D array along the rows

Consider the following program, what is the maximum value for frames generated at any given runtime? def identity_function(element): return element def square_function(element): return element * element def calculate_total(l, myfunc): total = 0; for element in l:t otal += myfunc(element) return total l = [1,2,3] print("the total for l is ", calculate_total(l, identity_function)) l = [1,2,3,4,5,6,7]print("the total for l is ", calculate_total(l,identity_function))

3

Consider the following diagram showing the runtime information. def print_n(n): if n>0: print(n) - print_(n-1) -> print(n) print_n(3) Frames print_n print_n n 3 print_n n 2 print_n n 1

3 2 1

Stack

A last-in-first-out (LIFO) abstract data type.

Which of the following is true of Polymorphism?

A method in a subclass can override the same method defined in its superclass.

Which of the following functions has a side effect?

All of the above

Broadcasting

Allows you to perform operations on arrays of different shapes.Refers to how numpy handles array of different dimensions while performing any arithmetic operation

Queu

An important ADT that follows first in first out methodology

How many dimensions can arrays have?

Any number, including zero (a scalar)

isFull()

Checks if the queue is full

try: num = int(input("Enter the number: ")) re = 100/num except ValueError: print(message from except ValueErr) except ZeroDvisionError: print("mssg from except ZDE") else: print("message from else") finally: print("message from finally") print("end")

Enter the number: ten message from except ValueError message from finally END

A finally clause is executed only when an exception is raised in a try suite.

False

According to the naming convention for variables, a variable has a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore, AND a variable can start with a digit.

False

Every variable has a type while it is declared in Python and it has NEVER been changed.

False

For a try/except statement, the statements in the except suite are executed after the statements in the try suite, only if no exceptions were raised

False

If a class has the same method as its superclass, both methods would be executed in turn: superclass's then subclass's.

False

In Python, a function cannot be passed as an argument assigned to a parameter of a function.

False

In Python, a programmer can combine data and code in a single object and this is called information hiding.

False

The python interpreter raises a runtime exception if an exception clause, that does not list any specific exception, is given before an exception clause that lists a specific exception.

False

When calling file_variable.write(string), the string value is directly copied to the disk where the file referenced by file_variable is located.

False

Writing data to a disk is faster than writing it to memory.

False

class Mammal: def __init__(self, species): self.__species = sprecies def show_species(self): print("I am a ", self.__species def set_species(self, species): self.__species = species def make_sound(self): print("Grrrrr") m = Mammal("cat") m.show_species() m.set_species("Dog") m.__species = "Fish" m.show_species() print("I am a ", m.__species) m._species = "Fish" m.show_species

I am a Cat I am a Dog I am a Fish I am a Dog

Consider the following program: class Alphabet: def __init__(self, value): self.__value = value How can you use @property decorator to implement the setter/getter for attribute __value?

Needed @value.setter above an implemented setter method, which should be defined "def value" and needed @property above an implemented getter, also defined "def value".

Consider the following program, which following output is correct: def add_more(l): l.append(50) print(l) myList = (10,20,30,40) add_more(myList) print(myList)

None of the above and a runtime error is generated

Consider the following function specification for the Hanoi Tower problem, which following statement is true based on the class' discussion? moveDiscs(n, fromPeg, tempPeg, toPeg)

Parameter n denotes disks 1, 2, ..., and n to be moved

What happens if the base condition isn't defined in recursive programs?

Program gets into an infinite loop.

Give one reason why a public attribute in a class is NOT good?

Public attributes can allow external corruption of the code, this is bad because if someone on purpose or accident, changes some code they can break the whole application. It is better to have a private attribute so it only changes that code inside the class, so if something breaks only the class will have a problem not the entire application.

Minimum maximum

Red < orange = True min(colors, key=lambda s:s.lower()) max(colors, key=lambda s:s.lower())

Which is not a step in Divide-Conquer-Glue?

Return immediate solution to the current subproblem

Negative step nums = [10...90] nums[::1]

Reverses everything nums[90...10]

Integer indexing

Select any arbitrary item based on the N-dimensional index. Also, each integer array is used to represent the number of indexes into that dimension

Consider the following program: which following output is correct:

Selling Price: 900 Selling Price: 900 Selling Price: 1000

How to extract a range of elements from an array?

Slicing!

Lambda function

The lambda function is anonymous function or a function having no name

The class CalendarClock inherits from multiple superclasses - classes Calendar and Clock, in that order. (This is a case of multiple inheritance). The method "time()" appears in both superclasses but not in the subclass. When an instance of class CalendarClock calls the method "time()", which of the two possibilities is executed?

The method in class Calendar.

What is the result of calling the "split" method on a string, as shown below?str = 'Roses are red'str_split = str.split( )

The string is split using space as delimiter and a list with three items is returned.

An immutable object is of the built-in types such as int, string, and tuple.

True

Forward engineering is the process of building from a high-level model or concept to build in complexities and lower-level details

True

In Python, Comparisons can be chained arbitrarily. So, a < b > c is a valid condition.

True

In Python, a function can be assigned to a variable.

True

Indirect recursion is when a function A calls a function B, which then calls function A.

True

Consider the following program. Which following output is correct? class Mammal: def __init__(self, species): self.__species = species def show_species(self): print("I am a ", self.__species) def make_sound(self): print("Grrrr") class Cat(Mammal): def __init__(self): Mammal.__init__(self,"Cat") def make_sound(self): print("Meow") def show_animal_sound(animal): animal.make_sound() animal_type = input() if animal_type == "Cat": animal = Cat() else: animal = Mammal("Mammal") show_animal_sound(animal)

Undecidable

Numpy function return either

Views (share data with og) or copies, np.copy and np.view

Slicing a = np.arange(10) print(a) 0 1 2 3 4 5 6 7 8 9 s = slice( 2, 7, 2) print( a[s] )

[ 2, 4, 6]

array1 = ([ 460.5, 460.5, 460.5]) print(array1.astype(np.uint16))

[[460, 460, 460]]

List comprehensions

a concise and convenient notation for creating new lists

Enqueu()

add/store item in queu

push()

adds element at the 'top' of the stack

Python Copy Module

allows to copy an object from one variable to another, copy.copy() and copy.deepcopy()

Negative indexing

allows to enumerate elements from the tail of a list

np.arange(1334, 1338) output?

array([1334, 1335, 1336, 1337])

In place operations modify the array a = array([[ 4, 15], [ 20, 75]]) b = array([[ 2, 5], [ 5, 15]]) print(a /= b)

array([[ 2, 3], [ 4, 5]])

Unpacking

automatically unpack a sequence allowing one to assign a series of induvial identifiers to the elements of the sequence

Logical operator return a ... a = array([ 1, 2, 3, 4, 5]) a > 2

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

substitution

can substitute, replace, and resize with slicing

isEmpty()

check if the queu is empty

Which following way is not correct to declare an attribute in a class to satisfy the information hiding?

declare a public attribute

Shallow copy copy.copy()

does NOT share data with og variable and is independent from original variable.

Arithmetic operations are... a = array([ 1, 2, 3]) b = array([ 4, 4, 10]) print( a * b)

element-wise array([ 4, 8, 30])

Input strings will consist of only three types of characters: vertical bars, open parentheses, and closing parentheses. Input strings contain one or more vertical bars followed by a set of matching parentheses (the "eye"), followed by one or more vertical bars. To check whether the "()" is centered, John wrote the following code: my_str = input() first_end = my_str.find("(") second_first = my_str.find(")") which following code can give John correct substrings before and after "()" respectively?

first_half = my_str[ : first_end] second_half = my_str[second_first+1:]

Filter

functions that receive other functions as arguments are a functional style capability called higher order functions

How broadcasting is done?

generally the smaller array is broadcast to the larger array in order to make their shapes compatible with each other

Assignment operator copys

just assigns some value from one variable to another. No new copy of the data gets created

Linked List

linear data structure, has nodes

Lambda syntax for filtering odd numbers

list(filter(lambda x: x% 2 != 0, number)) lambda parameter_list: expression

list comprehension syntax

list2 = [item for item in range(1,6)] print(list2) [1,2,3,4,5]

np.ones and np.zeroes(int, int)

makes a array out of ones or zeroes to (int (columns), int (rows) )

np.random.random(2, 3)

makes an array that has completely random numbers [[.321323, .12321, .009913] [.034293, .3123, .312308]]

class Portal: def __init__(self): self.__name = '' def method1(self: retrun self.__name def method2(self, val): self.__name = val def method3(self) del self.__name p = Portal(); p.n= "Hello World" print(p.n) del p.n Which following statement should be added at the end of class Portal so the above program can run correctly?

n=property(method1,method2,method3)

How to add two arrays together?

np.concatenate([array1, array2])

How are arrays typed?

np.uint8 np.int64 np.float32 np.float64

Consider the following program, what is the base case for the factorial function when factorial(3) is called for? def factorial(num): if num == 0: return 1 else:return num * factorial(num - 1)

num = 0;

Mapping syntax

numbers = [10,3,7,1,9,4,2,8,5,6] list(map(lambda x: x**2, numbers)) print(numbers) = [100,9,49,1,81,16,4,64,25,36]

filter syntax

numbers = [10,3,7,1,9] def is odd(x) return x % 2 != 0 list(filter(is_odd, numbers)) print(numbers) [3,7,1,9,5]

Boolean Indexing

pick elements from an ndarray based on some condition using comparison operators or some other operator

Indexing

python supports slice notation for any sequential data type such as list

Dequeu()

remove / access an item

pop()

removes the element most recently added to the stack and returns it

Peek()

return the item at the front without removing it

is_empty()

return true if empty, otherwise return false

np.ones_like() and np.zeros_like()

returns an array of given shape and type as a given array, with ones.

peek()

returns element at top of the stack (most recently added element)

size or len() of stack

returns number of elements on stack

Upcasting?

rounds up, uint64+uint16 = uint64, does NOT prevent overflow/underflow

Packing

series of comma separated objects without parenthesis are automatically packed into a single tuple

Slicing creates a...

shallow copy of the initial list

Deep copy copy.deepcopy()

shares data with og variable and changes the data of both at once

Slicing syntax

start:stop:step

2D lists

table: rows and columns a[0][1] # row index, column index

Slice object is used when

the same same slice is used many times

Mapping

use the built in function map to map a sequences values to new values

def swap_first(a,b): temp = a[0] a[0] = b[0] b[0] = temp which following driver code can successfully swap the first element of x and y at the end of the program?

x = [1,2,3] y = [4,5] print("x is ", x, " y is ",y) swap_first(x,y) print("x is ", x, " y is ",y)


Related study sets

Industrial Economics questions- Everything

View Set

KIV/ZI 1. ročník FEK, Teorie ke zkoušce ze ZI

View Set

ECO - Ch.18 - Open-Economy Macroeconomics: Basic Concepts

View Set

Political Ideologies "Nationalism" Chapter 6

View Set

Ch 7 Intrest Groups and Political Parties

View Set

Chapter 7: Requirements -> Behavior Driven Design

View Set

VIRGINIA v. BLACK (538 U.S. 343)

View Set

Gestalt Theory and Therapy - Chapter 6

View Set