Python Year Final

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Consider the following code snippet: def isEven(num) : if num % 2 == 0 : return True else : return isOdd(num) def isOdd(num) : if num % 2 == 1 : return True else : return isEven(num) For any given value of num, what is the maximum number of function calls that could occur?

2

Consider the following mergeSort function: def mergeSort(values) : if len(values) <= 1 : return mid = len(values) // 2 first = values[ : mid] second = values[mid : ] mergeSort(first) mergeSort(second) mergeLists(first, second, values) # The implementation of mergeLists has been omitted. # It can be found in the textbook. If the function takes 1.0 seconds to sort a list of 10,000 elements, how long would you expect it to take to sort a list of 20,000 elements?

2.2 seconds

How many squares are drawn by the following code segment? def tSquare(width, x, y, canvas) : canvas.drawRect(x, y, width, width) if width >= 4 : tSquare(width / 2, x, y, canvas) tSquare(width / 2, x + width / 2, canvas) tSquare(width / 2, x, y + width / 2, canvas) tSquare(width / 2, x + width / 2, y + width / 2, canvas) # Code to setup the canvas has been omitted tSquare(0, 0, 16, canvas)

21

Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] if len(word) == 0 : result.append(word) return result else: for i in range(len(word)) : shorter = word[ : i] + word[i + 1 : ] shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result How permutations will be generated by calling permutations("code")?

24

Consider the following code segment for computing Fibonacci numbers. How many times is fib(3) computed in order to compute fib(7)? def fib(n) : if n <= 2 : return 1 else : return fib(n - 1) + fib(n - 2)

5

Consider the following function for performing a linear search: def linearSearch(values, target) : for i in range(len(values)) : if values[i] == target : return i return -1 How many elements will be visited when values is [1, 5, 7, 6, 2, 4, 9, 3, 8, 0] and target is 2?

5

How many squares are drawn by the following code segment? def tSquare(width, x, y, canvas) : canvas.drawRect(x, y, width, width) if width >= 4 : tSquare(width / 2, x, y, canvas) tSquare(width / 2, x + width / 2, canvas) tSquare(width / 2, x, y + width / 2, canvas) tSquare(width / 2, x + width / 2, y + width / 2, canvas) # Code to setup the canvas has been omitted tSquare(0, 0, 8, canvas)

5

Consider the recursive function myPrint: 1. def myPrint(n) : 2. if n < 10 : 3. print(n) 4. else : 5. m = n % 10 6. print(m) 7. myPrint(n / 10) What is printed for the call myPrint(8)?

8

Which statement about classes is true?

A class describes a set of objects that all have the same behavior.

What is returned when scipi.io.wavfile.read is called?

A tuple containing the sample rate and the sound data

Consider the following function call for computing a linear regression: result = scipy.stats.linregress(data1, data2) What is stored in result when this function call completes?

A tuple containing the slope, intercept and correlation coefficient for the data sets.

Which of the following statements is true? -A programmer cannot create an instance a concrete class. You Answered -A programmer cannot create an instance of an abstract class. -Abstract classes are designed to force programmers to create subclasses. -Calling any method defined in an abstract class will raise a NotImplementedError exception.

Abstract classes are designed to force programmers to create subclasses.

What portable file format is commonly used to export data from a spreadsheet so that it can be read and processed by a Python program?

Comma-Separated Values (CSV)

Recursion will take place if any of the following happen: I. function A calls function B, which calls function C II. function A calls function B, which calls function A III. function A calls function A

II and III

Which of the following statements about recursion is correct?

In many cases, a recursive solution will be easier to understand and to implement than an iterative solution.

Which sorting algorithm was enhanced to create Shell sort?

Insertion sort

What type of value is returned by the expression ord("A")?

Integer

Parameter variables should not be changed within the body of a function because

It is confusing because it mixes the concept of a parameter with that of a variable

Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area What will happen if lines 4 and 5 are replaced with the following lines of code? if sideLength == 1 : return 2

It would increase the result calculated by the function for all calls except those where sideLength <= 0

The checklist function is shown below: def checklist(lst) : if(lst[0] >= lst[len(lst)-1] : return True return False What can you conclude about the running time of this function?

Its running time will be O(1).

Consider the following code segment that examines the elements of two lists: matches = 0 for i in range(len(lst1)) : for j in range(len(lst2)) : if lst1[i] == lst2[j] : matches = matches + 1 What can you conclude about the running time of this code segment if both lists contain n elements?

Its running time will be O(n^2).

Which of the following patterns can be used for designing your class to update the balance of a bank account?

Keeping a total

Which sorting algorithm has better than O(n2) behavior, even in the worst case?

Merge sort

How can you read from a file starting at a designated position in it?

Move the file marker prior to a read or write operation.

Can you search the following list using binary search? values = [6, 5, 2, 4, 0, 1, -17, -1]

No. Binary search can only be applied to a sorted list.

The following function is supposed to return -1 when x is negative, +1 when x is positive, or 0 if x is zero. What, if anything, is wrong with the function? def plusMinusZero(x) : if x == 0 : return 0 elif x <= 0 : return -1 else x >= 0 : return 1

Nothing is wrong with the function

Consider the following big-Oh growth rates: O(1) O(2^n) O(n) O(n^2) Which big-Oh growth rate is least desireable?

O(2^n)

Consider the following function, which correctly merges two lists: def mergeLists(first, second, values) : iFrist = 0 iSecond = 0 j = 0 while iFirst < len(first) and iSecond < len(second) : if first[iFirst] < second[iSecond] : values[j] = first[iFirst] iFirst = iFirst + 1 else : values[j] = second[iSecond] iSecond = iSecond + 1 j = j + 1 while iFrist < len(first) : values[j] = first[iFirst] iFirst = iFirst + 1 j = j + 1 while iSecond < len(second) : values[j] = second[iSecond] iSecond = iSecond + 1 j = j + 1 What is the big-Oh complexity of this algorithm, where n is the total number of elements in first and second?

O(n)

Consider the following function which determines whether or not a list contains any repeated values: def hasDuplicate(data) : for i in range(len(data)) : for j in range(i + 1, len(data)) : if data[i] == data[j] : return True return False What is the big-Oh complexity of this algorithm, where n is the number of elements in data?

O(n^2)

Consider a list of 10 elements that is being sorted into ascending order using the selection sort algorithm. What is guaranteed to be true after the algorithm's outter loop has finished executing for the first time?

One element will be in the correct place

How many constructors can be defined for each class?

Only one may be defined

Which of the following statements is not true?

Splitting a large program into multiple files can make the program run more quickly.

What can specify the address of a web application and the arguments that must be supplied to get it to produce the desired result?

The Application Programming Interface (API)

Which of the following is NOT true about constructors?

The constructor is defined using the special method name __default__

Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] if len(word) == 0 : result.append(word) return result else: for i in range(len(word)) : shorter = word[ : i] + word[i + 1 : ] shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result What is the base case for this function?

The empty string

Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] if len(word) == 0 : result.append(word) return result else: for i in range(len(word)) : shorter = word[ : i] + word[i + 1 : ] shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result What is the base case for this function?

The empty string

When your program contains logic to read one or more files, which of the following statements is NOT true about the error handling logic needed:

The file name might be too long

The following program is supposed to display a message indicating if the integer entered by the user is even or odd. What is wrong with the program? num = int(input("Enter an integer: ")) print("The integer is", evenOdd(num)) def evenOdd(n) : if n % 2 == 0 : return "even" return "odd"

The function definition must appear before the function is called.

Consider the selection sort function shown below: def selectionSort(values) : for i in range(len(values)) : minPos = minimumPosition(values, i) swap(values, minPos, i) The function works correctly in its current form. What would happen if the line calling swap was replaced with: swap(values, i, minPos)?

The list would still be sorted, using the same number of iterations

What does an object reference specify?

The location of an object

Which statement about this code snippet is accurate? years = 50 balance = 10000 targetBalance = 20000 rate = 3 for i in range(1 , years + 1) : if balance >= targetBalance : i = years + 1 else : interest = balance * rate / 100 balance = balance + interest

The loop will run 50 times.

Assume we are using quicksort to sort a list into ascending order. Where does quicksort place the pivot element after partitioning the list?

The pivot element is placed in its final correct location.

Which statement is correct about the public interface for a class?

The public interface for a class is the set of all methods provided by a class, together with a description of their behavior.

Which statement about if statements is not correct?

The statements in a statement block must be indented 2 spaces more than the header.

The following function is supposed to add 1 to every element in a list of integers. def addOne(values) : for i in range(len(values)) : values[i] = values[i] + 1 What is wrong with the following function?

There is nothing wrong with the function. It works as intended.

Which of the following is NOT a valid exception in Python?

TryError

Which character encoding standard uses sequences of between 1 and 4 bytes to represent a huge number of different characters?

UTF-8

How can you make sure the elements in a set will be printed in sorted order?

Use the sorted function when printing the set

Given the following code snippet, what are the contents of the list names? firstNames = ["Joe", "Jim", "Betsy", "Shelly"] names = firstNames * 2

["Joe", "Jim", "Betsy", "Shelly", "Joe", "Jim", "Betsy", "Shelly"]

Consider the selection sort function and function call shown below: def selectionSort(values) : for i in range(len(values)) : print(values) minPos = minimumPosition(values, i) swap(values, minPos, i) data = [1, 2, 3] selectionSort(data) print(data) What is displayed when this code segment executes?

[1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3]

Consider the selection sort function and function call shown below: def selectionSort(values) : for i in range(len(values)) : print(values) minPos = minimumPosition(values, i) swap(values, minPos, i) data = [9, 1, 7, 2] selectionSort(data) print(data) What is displayed when this code segment executes?

[9, 1, 7, 2] [1, 9, 7, 2] [1, 2, 7, 9] [1, 2, 7, 9] [1, 2, 7, 9]

Consider the following class which will be used to represent complex numbers: class Complex: def __init__(self, real, imaginary): self._real = real self._imaginary = imaginary def ____________________: real = self._real + rhsValue._real imaginary = self._imaginary + rhsValue._imaginary return Complex(real, imaginary) What code should be placed in the blank so that two complex numbers can be added using the + operator?

__add__(self, rhsValue)

What method name is used for a constructor?

__init__

Which method must a user-defined class implement in order for list's sort method to work correctly?

__lt__

What is the name of the instance variable in the following code segment? class Fruit : def getColor(self) : return self._color

_color

Consider the following class: class Pet: ____________________ def __init__(self, name): self._name = name Pet._lastID = Pet._lastID + 1 self._registrationID = Pet._lastID What line of code should be placed in the blank to create a class variable that keeps track of the most recently used registration identifier?

_lastID = 0

Consider the following problem: A grocery store carries a wide variety of products that fall into broad categories such as fruit, milk and toys. Each category contains many items. For example, the fruit category contains items like apples, oranges and bananas while the milk category contains items like skim, 2% and chocolate, and the toys category includes items like balls, dolls and trucks. A program for the grocery store needs to be able to add new items to a category, remove items from a category and display all of the items in a category. The order in which the items are displayed is not important. Which container or structure best solves this problem?

a dictionary of sets

Complete the code for the calcPower recursive function shown below, which is intended to raise the base number passed into the function to the exponent power passed into the function: 1. def calcPower(base, exponent) : 2. answer = 0 3. if exponent == 0 : 4. answer = 1 5. else : 6. _____________________________ 7. return answer

answer = base * calcPower(base, exponent - 1)

What is output by the following code segment when input.txt contains the following words: apple, pear, and banana stored one per line? infile = open("input.txt", "r") for word in infile : print(word)

apple pear banana

Which of the following statements indicates that ClassA is a superclass of ClassB?

class ClassB(ClassA) :

Consider a class that represents a hardware device. The device can be in one of two states: Plugged in, or unplugged. Which of the following class definitions is best for this situation?

class Device : PLUGGED_IN = 0 UNPLUGGED = 1 def __init__(self) : . . .

Which group of classes is poorly designed?

class Dog : . . . class Cat(Dog) : . . .

You are creating a Motorcycle class which is supposed to inherit from the Vehicle class. Which of the following class declaration statements will accomplish this?

class Motorcycle(Vehicle) :

What method ensures that the output has been written to the disk file?

close()

The flowchart shows the order in which steps should be executed, and the diamond-shaped boxes indicate:

decision statements

Consider the following code segment: done = False while not done : try : filename = input("Enter the file name: ") inFile = open(filename, "r") ____________________ except IOError : print("Error: File not found.") It is supposed to keep on prompting the user for file names until the user provides the name of a file that can be opened successfully. What line of code should be placed in the blank to achieve this goal?

done = True

You are creating a program that includes a dictionary where the keys are people's names and the values are their favorite foods. Which of the following statements adds an entry to the dictionary that indicates that Ravi's favorite food is chocolate?

favoriteFoods["Ravi"] = "chocolate"

Which of the following file operations is NOT valid for reading a binary file?

fileName = open("input.dat", "rw")

Which of the following statements stores seafood in the food variable if Joe is not a key in the favoriteFoods dictionary?

food = favoriteFoods.get("Joe", "seafood")

How can you print all the elements in the set colors each on a separate line?

for color in colors : print(color)

Consider the following class: class Counter : def getValue(self) : return self._value def click(self) : self._value = self._value + 1 def unClick(self) : self._value = self._value - 1 def reset(self) : self._value = 0 Which method is an accessor?

getValue

Which of the following statements checks to see if the key Apple is already in the dictionary fruit?

if "Apple" in fruit :

What is missing from this code snippet to find the longest value in the list? colors = ["red", "purple", "blue", "green", "yellow", "light green"] longest = colors[0] f or i in range(1, len(colors)) : _____________________ longest = colors[i]

if len(colors[i]) > len(longest) :

Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] ____________________ result.append(word) return result else: for i in range(len(word)) : shorter = word[ : i] + word[i + 1 : ] shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result In the textbook, the line now represented by the blank was if len(word) == 0 :. What line of code could be used instead to achieve the same list of permutations?

if len(word) == 1 :

Which statement correctly compares these two lists for equality? nums = [1, 2, 3, 4, 5] nums2 = [5, 4, 3, 2, 1]

if nums == nums2

Which of the following if statements is problematic because of the limited precision of floating-point numbers?

if sqrt(2) * sqrt(2) == 2.0 :

In a sorting algorithm, it may be necessary to find the position of the maximum element in a list, starting from some initial position, start. What code should be placed in the blank to complete the maximumPosition function? def maximumPosition(values, start) : maxPos = start for i in range(start + 1, len(values)) : ____________________ maxPos = i return maxPos

if values[i] > values[maxPos] :

Which of the following is NOT true about sets?

in a set, elements are stored in the order they are added

Which of the following statements opens a binary file for reading?

inFile = open("test.dat", "rb")

Which of the following statements is NOT valid for reading from a file:

inputFile.readline(5)

Consider the following code snippet: def sort(values) : for i in range(1, len(values)) : next = values[i] j = i while j > 0 and values[j-1] > next : values[j] = values[j - 1] j = j - 1 values[j] = next What sort algorithm is used in this code?

insertion sort

Which of the following is not a function that resides in Python's os module?

open

Assume that the address variable currently holds the URL for webpage. Which statement(s) store a structured representation of that webpage in the doc variable?

response = urllib.request.urlopen(address) doc = bs4.BeautifulSoup(response)

Consider the following class definitions: class Vehicle : . . . def __init__(self) : self._numAxles = 0 . . . def setAxles(self, num) : self._numAxles = num . . . class Motorcycle(Vehicle) : def __init__(self) : super().__init__() ________________________ Which statement should be placed in the blank so that all motorcycles have 2 axles?

self.setAxles(2)

Which code snippet is the correct Python equivalent to the following Algebraic expression ? c = √(a2 + b2)

sqrt(a ** 2 + b ** 2)

Assuming the Rectangle class is already designed with a constructor __init__(self, x, y, width, height), which code snippet creates a square in the middle of a frame with FRAME_WIDTH = 400, FRAME_HEIGHT = 600?

square = Rectangle(FRAME_WIDTH/2 - 50, FRAME_HEIGHT/2 - 50, 100, 100)

Class variables are also known as:

static variables

To use or call a function, you need to specify:

the function name and its arguments

For the list: prices = [10.00, 15.50, 13.25, 20.15], what value is contained in prices?

the location of the list

A subclass object can always be used when a superclass object is expected. This fact is referred to as:

the substitution principle

Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area Assume that line #5 is changed to this: smallerArea = triangleArea(sideLength) This would cause infinite recursion for __________________________________

triangles with sideLength greater than or equal to 1

Which of the following statements stores the current position of the file marker for inFile into x?

x = inFile.tell()

Which statement creates an empty set and stores it in x?

x = set()


Ensembles d'études connexes

Price Ceilings and Price Floors - Assignment #7

View Set

Anatomy (2023) - SEM 1 Exam Review

View Set

Principles of Management CLEP Exam

View Set

Praxis PLT Study Guide (5622) part 1

View Set