Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

Sample Final Exam for CSE30 Spring/2023

1) Given a custom Python class A, how can we make class A abstract?

a) custom Python classes are always abstract

b) specify the "abstract" keyword in one of its methods

c) specify "raise NotImplemented()" in one of its methods

ANSWER: c)

2) Given a custom Python class A and subclasses B, C, and D that all contain a method op() with the same code.

Where would be the preferred class to specify the method op() and its implementation?

a) include op() only in A

b) include op() in B, C, and D

c) no preferred location

ANSWER: a)

3) Given a custom Python class A and its subclasses B, C, and D, where all four classes contain a method op().

How can we ensure that the method op() in class A cannot be executed:

a) make the method op() in class A abstract

b) we don't need to do anything in particular

c) it's not possible to do this

ANSWER: a)

4) Given a custom Python class A and this code snippet:

myobj1 = A()

x = myobj1 + 7

y = 7 + myobj1

We can ensure that the preceding statements succeed by:

a) implementing the __add__() method

b) implementing the __radd__() method

c) both a) and b)

d) no need for extra code

ANSWER: c)

5) Queues are useful for the following types of use cases:

a) scheduling tasks for execution (e.g., processes)

b) checking if expressions contain balanced parentheses

c) both a) and b)

d) almost any type of use case involving trees

ANSWER: c)

6) Stacks are useful for the following types of use cases:

a) handling prefix and postfix expressions

b) checking if expressions contain balanced parentheses

c) both a) and b)

d) almost any type of use case involving trees

ANSWER: c)

7) A custom Python generator will:

a) include the yield keyword

b) be more efficient in terms of memory usage

c) both a) and b)

d) does not have particular advantages

ANSWER: c)

8) Algorithms for graphs typically restrict graphs so that they:

a) exclude only negative cycles

b) exclude any type of cycle

c) both a) and b)

d) nothing is excluded

ANSWER: c)

9) An acyclic graph is a graph without:

a) vertices

b) edges

c) cycles

d) tree

ANSWER: c)

10) A graph is a tree if and only if:

a) Every pair of vertices in the graph is connected by exactly one edge.

b) The graph contains a single cycle.

c) There is a unique path between every pair of vertices in the graph.

d) There are no cycles in the graph, and it is connected.

ANSWER: d)

11) Suppose you have a graph represented as an adjacency list in Python. A key-value pair represents an edge from the key vertex to the value vertex. Which of the following Python code snippets does not return the correct number of vertices in the graph?

graph = {

'A': ['B', 'C'],

'B': ['A', 'C', 'D'],

'C': ['A', 'B'],

'D': ['B']

}

a) len(graph)

b) len(graph.keys())

c) len(graph.values())

d) sum(len(adj_list) for adj_list in graph.values())

ANSWER: d)

12) Suppose you have a graph represented as an adjacency list in Python. Which of the following Python code snippets returns the number of edges in the graph?

graph = {

'A': ['B', 'C'],

'B': ['A', 'C', 'D'],

'C': ['A', 'B'],

'D': ['B']

}

a) sum(len(adj_list) for adj_list in graph.keys())

b) sum(len(adj_list) for adj_list in graph.values())

c) len(graph.keys()) - len(graph)

d) sum(len(adj_list) for adj_list in graph.values()) + len(graph)

ANSWER: b)

13) Consider the following Python program:

class Shape:

def __init__(self, sides):

self.sides = sides

def area(self):

pass

class Triangle(Shape):

def __init__(self, sides):

super().__init__(sides)

def area(self):

a, b, c = self.sides

s = (a + b + c) / 2

area = (s * (s - a) * (s - b) * (s - c)) ** 0.5

return area

Which of the following code snippets correctly creates an instance of the Triangle class and calculates its area?

a)

sides = [3, 4, 5]

triangle = Triangle()

result = triangle.area(sides)

b)

sides = [3, 4, 5]

triangle = Triangle(sides)

result = triangle.area()

c)

sides = [3, 4, 5]

triangle = Shape(sides)

result = triangle.area()

d)

sides = [3, 4, 5]

triangle = Shape()

result = triangle.area(sides)

ANSWER: b)

14) Which of the following statements accurately describes class inheritance in Python?

a) Inheritance allows a class to inherit attributes and methods from multiple parent classes simultaneously.

b) Inheritance can only apply to a base class and a child class. The base class cannot be inherited from other (parent) classes.

c) Inheritance is a mechanism that allows a class to inherit attributes and methods from another class, creating a hierarchical relationship between them.

d) Inheritance is only applicable to built-in classes in Python and cannot be used with user-defined classes.

ANSWER:

15) Which data structure is the most suitable to implement a LIFO (Last-In, First-Out) policy?

a) Graph

b) Queue

c) Stack

d) Set

ANSWER: c)

16) What is the purpose of the try-except block?

a) It is used to define a block of code that will always be executed in a different scope.

b) It is used to specify code that should be executed in a predefined order.

c) It is used to handle and recover from exceptions that may occur during code execution.

d) It is used to improve code performance by avoiding exception handling.

ANSWERL: c)

17) The following function

def f(n):

i = 0

while i < n:

yield 2 * i

i += 1

a) returns the first n even numbers.

b) is an infinite loop because the while statement does not have a stopping condition.

c) generates all integers smaller than n.

d) generates even numbers smaller than n.

ANSWER: d)

18) The following recursive function takes a single parameter h (a list) and def g(h):

if len(h) == 0:

return [[]]

else:

i = g(h[1:])

return i + [[h[0]] + x for x in i]

a) returns the reversed list.

b) returns the set of all possible subsets of h.

c) returns the first half of the list.

d) returns every other element in the original list, starting from the element at index 1.

ANSWER: b)

19) Which method in the random module of Python can be used to generate a random sample from a given population without replacement?

A) random_sample()

B) sample()

C) choice()

D) shuffle()

answer: B)

20) What is the purpose of a sliding window in Python?

A) To efficiently search for a specific element in a list.

B) To calculate the sum of a subarray with a fixed length.

C) To sort a list in ascending order.

D) To remove duplicates from a sequence.

answer: B)

21) Check the code below and correct the bug.

def sliding_window_averagerator(nums, k):

result = []

window_sum = 0

window_size = 0

for i in range(len(nums)):

window_sum += nums[i]

window_size += 1

if window_size == k:

result.append(window_sum / k)

window_sum -= nums[i - k + 1]

window_size -= 1

return result

Bug: it fails to handle the case when the window size (k) is greater than the length of the nums list. This will lead to an IndexError when trying to access nums[i - k + 1] in the line window_- sum -= nums[i - k + 1].

Options:

A) Add a condition to check if k is greater than the length of nums and return an appropriate message or raise an exception.

B) Set the window size to the minimum value between k and the length of nums to avoid going beyond the index limits.

C) Adjust the iteration range to range(len(nums) - k + 1) to ensure that the loop does not iterate beyond the available elements.

D) Add a condition to break the loop if i - k + 1 becomes less than 0 to avoid accessing elements outside the list.

answer: B)

22) What is the purpose of the subplots() function in Matplotlib?

A) To create multiple subplots within a single figure.

B) To adjust the subplot spacing and margins.

C) To save the figure as an image file.

D) To create a secondary axis for a specific plot.

answer: A)

Q23 & 24) Refer to the matplotlib example below, import matplotlib.pyplot as plt

products = ['Product A', 'Product B', 'Product C', 'Product D']

sales = [500, 750, 300, 900]

plt.bar(products, sales)

plt.xlabel('Products')

plt.ylabel('Sales (in units)')

plt.title('Product Sales Performance')

plt.show()

Q23) In the given Matplotlib example, how can you change the color of the bars to green?

A) Use the color parameter in the bar() function.

B) Use the set_color() method on the bar objects.

C) Use the set_facecolor() method on the bar objects.

D) Use the color parameter in the show() function.

answer: C)

Q24) What does the xlabel() function in the example code do?

A) Sets the title of the plot.

B) Labels the x-axis of the plot.

C) Creates a legend for the x-axis for the plot.

D) Adjusts the figure size of the plot.

answer: B)

Q25) What is a dependency in the context of task scheduling?

A) A task that is executed after all other tasks.

B) A task that relies on the completion of another task before it can be executed.

C) A task that can be executed concurrently with other tasks.

D) A task that has a fixed start and end time.

answer: B)

Q26) Which data structure is commonly used to represent task dependencies in Python?

A) List

B) Dictionary

C) Set

D) Stack

answer: B)

Q27) Given the definition of topological sorting,

Topological sorting is a technique used to order the nodes of a directed graph in such a way that for every directed edge (u, v), node u comes before node v in the ordering. In other words, it is a linear ordering of the graph's nodes that respects the dependencies between the nodes.

What is the purpose of a topological sorting algorithm in task scheduling with dependencies?

A) To determine the total execution time of all tasks.

B) To find the task with the longest duration.

C) To determine the order in which tasks should be executed based on their dependencies.

D) To calculate the critical path of the project.

answer: C)

Q28) Consider a directed graph representing tasks and their dependencies. The graph has the following dependencies:

Task A has no dependencies.

Task B depends on Task A.

Task C depends on Task B.

Task D depends on Task A and Task C.

Which of the following represents the correct order of executing the tasks?

A) A, B, C, D

B) A, B, D, C

C) A, C, B, D

D) A, D, C, B

Correct answer: C) A, C, B, D

Q29)What is the main difference between a generator and a function in Python?

A. Generators can produce multiple values, while functions can only produce one value.

B. Generators can be called anywhere, while functions can only be called where they are defined.

C. Generators can produce values one at a time in a loop, while functions must produce all values at once.

D. Generators can accept parameters, while functions cannot.

Answer: C

Q30)How can you invoke a generator object created using a generator function in Python?

A. call()

B. invoke()

C. execute()

D. next()

Answer: D

Q31)What is the main difference between a generator expression and a list comprehension?

A. List comprehensions return the entire list, and the generator expression returns only the generator object

B. Generator expressions can only be used for numerical calculations, while list comprehensions can be used for any type of data.

C. Generator expressions use square brackets, while list comprehensions use parentheses.

D. Generator expressions have a more concise syntax compared to list comprehensions.

Answer: A

Q32)What specific condition must a recursive function include to terminate recursion?

a) return statement

b) loop statement

c) conditional statement

d) increment statement

Answer: c

Q33)During the process of recursion, each recursive call:

a) Creates a new function

b) Allocates new variables in memory

c) Returns a result to the calling function

d) Blocks program execution

Answer: a

Q34)The advantages of recursion include:

a) Conciseness and readability

b) Better performance

c) Easier debugging

d) Avoiding the use of loops Answer: a

Q35)In a recursive function, what happens if there is no explicit termination condition?

a) The function will infinitely loop by calling itself

b) The function will immediately return a result

c) The function will throw an exception

d) The function will modify the parameters passed to it

Answer: a

Q36)In Python, which keyword is used to invoke a parent class method?

a) super()

b) parent()

c) base()

d) self()

Answer: a

Q37)Which option describes the concept of a class method?

a) A method that can only be called by class instances

b) A method that can only be called by the class itself

c) A method that can only be accessed by class variables

d) A method that can only be accessed by object instances

Answer: b

Q38)Which method should you use to obtain all the keys from a dictionary?

a) keys()

b) get_keys()

c) key_values()

d) items()

Answer: a

Q39)How can you check if a key exists in a dictionary?

a) exists(key)

b) contains(key)

c) in keyword

d) has_key(key)

Answer: c

Q40)What type should the keys (key) of a dictionary be in Python?

a) Strings (str)

b) Integers (int)

c) Floating-point numbers (float)

d) Any hashable type

Answer: d