Python II Flashcards
(100 cards)
Which of the following statements accurately describe Lambda functions in Python? a. They are a concept from functional programming, originating from Alonzo Church’s λ-calculus . b. They can have several arguments, but are limited to a single expression . c. Every Lambda function can be rewritten using a regular def function definition . d. They are primarily used for defining functions that will be called multiple times throughout a large codebase .
a, b, c
Consider the following Python code snippet: my_lambda = lambda a : a + 10 print(my_lambda(5)) Which of the following regular function definitions is equivalent to my_lambda? a. def my_lambda(a): return a + 10 b. def my_lambda(a): print(a + 10) c. def my_lambda(): return 10 d. def my_lambda(a): return a - 10
a
Lambda functions are often used as arguments to higher-order functions. Which of the following built-in Python functions or modules can directly benefit from the use of a Lambda function as an argument, as shown in the lecture slides? a. map() b. filter() c. reduce() (from functools) d. sum()
a, b, c
Given the list people = [‘Alice’, ‘Bob’, ‘Charlie’], which of the following uses of sort() with a lambda function would sort the list by the length of the person’s name? a. people.sort(key=lambda x : x) b. people.sort(key=lambda x : x) c. people.sort(key=lambda x : len(x)) d. people.sort(key=lambda x : len(x))
c
When working with complex objects, such as instances of a custom class, lambda functions can be particularly useful for sorting or finding minimum/maximum values. Consider the Person class from the slides: class Person: def __init__(self, name, age): self.name = name self.age = age jack = Person(‘Jack’, 30) agnes = Person(‘Agnes’, 28) students = [jack, agnes] Which of the following correctly uses a lambda function to find the person with the minimum age in the students list? a. min_age = min(students, key=lambda s: s.name) b. min_age = min(students, key=lambda s: s.age) c. min_age = min(students.age) d. min_age = min(students, key=lambda s: len(s.name))
b
Which of the following Python constructs are considered “Callable Objects” as discussed in the lectures? a. Functions, such as print() b. Methods, such as some_list.sort() c. Classes (their constructors), such as my_dog = Dog() d. Instances of a class that implement the __call__ magic method
a, b, c, d
Consider the Logger class implementation from the slides: class Logger: def __init__(self, prefix): self.prefix = prefix def __call__(self, message): print(f’{self.prefix}: {message}’) info_logger = Logger(‘INFO’) debug_logger = Logger(‘DEBUG’) Which of the following statements are true regarding this code? a. info_logger and debug_logger are instances of the Logger class that can be called like functions . b. The __call__ method allows instances of Logger to store a state (e.g., prefix) that is reused across calls without being passed as an argument . c. Calling info_logger(‘System boot’) would print ‘INFO: System boot’ . d. The Logger class is an example of a decorator.
a, b, c
Which of the following statements about decorators in Python are correct? a. Decorators are functions that take one or more functions as arguments and return a new function that modifies the behavior of the original . b. The @ syntax is syntactic sugar for manually wrapping a function with a decorator . c. Decorators implemented as classes can be useful for maintaining state between calls to the decorated function . d. The functools.wraps decorator is essential for preserving the __name__ and __doc__ attributes of the original function .
a, b, c, d
Consider the functools.cache decorator. Which of the following accurately describes its behavior when applied to a recursive function like fibonacci(n)? from functools import cache @cache def fibonacci(n): # … (implementation for fibonacci) … a. It stores the return values of the function based on its arguments . b. For repeated calls with the same arguments, it returns the cached result without re-executing the function’s body . c. It is useful for optimizing functions with potentially expensive computations for repeated inputs . d. It automatically detects and resolves infinite recursion.
a, b, c
The functools.singledispatch decorator allows a function to behave differently based on the type of its first argument. Consider the example: from functools import singledispatch @singledispatch def display(x) -> None: raise NotImplementedError @display.register def _(x: list | tuple): for i, item in enumerate(x): print(f’Item {i}: {item}’) @display.register def _(x: dict): for key, value in x.items(): print(f’{key}: {value}’) my_list = [1, 2, 3] my_dict = {‘a’: 1, ‘b’: 2} Which of the following will correctly execute and produce output? a. display(my_list) b. display(my_dict) c. display(10) (assuming no other registrations for int) d. display(‘hello’) (assuming no other registrations for str)
a, b (c and d would raise NotImplementedError unless int or str were registered.)
Asynchronous functions in Python, using async and await, are primarily designed for which type of concurrency? a. CPU-bound tasks, leveraging multiple CPU cores in parallel . b. I/O-bound tasks, allowing the program to perform other operations while waiting for I/O to complete . c. Simultaneously executing heavy mathematical computations on multiple GPUs. d. Distributing computations across a cluster of machines.
b
Consider the sequential vs. asynchronous image download example from the UE slides. Why does the asynchronous version significantly reduce the total execution time compared to the sequential one, especially for a large number of images? a. The asyncio.sleep() function is much faster than time.sleep(). b. Asynchronous functions automatically download images in parallel across multiple CPU cores. c. The await keyword signals to the event loop that the function is waiting for an I/O operation (network request) to complete, allowing other tasks to run in the meantime instead of idling . d. aiohttp automatically compresses image files before downloading, reducing transfer size.
c
Which of the following statements are true about image data representation? a. Grayscale 2D images are typically represented as 2D arrays, with each pixel carrying brightness information . b. RGB 2D images are represented as 3D arrays, with two spatial dimensions and one dimension for color channels (red, green, blue) . c. The Alpha channel in RGBA images typically represents transparency information . d. Image data is exclusively stored as vector graphics.
a, b, c
Which of the following image file formats uses lossless compression and is vector-based, making it suitable for line plots and neural network architecture depictions without loss of resolution when zooming? a. JPEG b. PNG c. SVG d. GIF
c
When working with matplotlib, which of the following components are correctly described? a. A ‘Figure’ represents the window you are plotting in, and it can be saved to image files . b. ‘Axes’ refer to the x-axis and y-axis lines on a plot . c. An ‘Axes’ object is what you plot on, and a Figure can contain multiple Axes . d. Matplotlib only supports plotting in an interactive mode where plots are shown immediately.
a, c
Consider the following Matplotlib code snippet for creating a basic line plot: import matplotlib.pyplot as plt import numpy as np t = np.arange(0, 100) fig, ax = plt.subplots() ax.plot(t) ax.set_xlabel(‘Label for x’) ax.set_ylabel(‘Label for y’) fig.suptitle(‘Title of the figure’) plt.show() Which of the following statements are correct about this code? a. plt.subplots() returns a Figure object (fig) and an Axes object (ax) . b. ax.plot(t) adds a line to the Axes object . c. fig.suptitle() sets a super-title for the entire figure window . d. This example demonstrates the pyplot style, where pyplot implicitly manages figures and axes.
a, b, c (d is incorrect, it shows the object-oriented style. The plt.plot(t); plt.show() without fig, ax = plt.subplots() would be more pyplot-style )
Given the following Matplotlib code for creating multiple subplots: fig, ax = plt.subplots(2, 3) # ax is a 2x3 array of Axes ax[0, 0].plot(t) ax[0, 1].plot(t) ax[1, 0].plot(-t) ax[1, 2].plot(t, label=’data t’) ax[1, 2].plot(-t, label=’data -t’) ax[1, 2].legend() fig.tight_layout() plt.show() Which of the following statements are true? a. The code creates a figure with 6 subplots arranged in 2 rows and 3 columns . b. The legend will appear on ax[1, 2] because legend() is called on that specific Axes object after plots with labels are added to it . c. fig.tight_layout() adjusts subplot parameters for a tight layout, preventing labels from being clipped . d. It’s not possible to plot multiple lines on the same Axes object (e.g., ax[1,2] plotting t and -t).
a, b, c
When displaying scalar image data (e.g., a 2D grayscale array) with ax.imshow() in Matplotlib, how is color typically assigned to values by default? a. By randomly assigning colors to pixels. b. Using a colormap that maps values to colors . c. The image is displayed in its original colors, regardless of it being scalar data. d. Only black and white are used to represent the lowest and highest values, respectively.
b
Which of the following plotting libraries is known for offering interactive plots and is particularly useful for web applications like Dash or Shiny? a. Matplotlib b. Seaborn c. Plotly d. Altair
c
Which of the following statements are true regarding the use of Seaborn? a. Seaborn is built on top of Matplotlib, acting as a high-level interface . b. It is particularly optimized to work well with Pandas DataFrames . c. sns.set_theme() applies a default aesthetic theme to plots . d. Seaborn’s pairplot() is useful for visualizing pairwise relationships in a dataset .
a, b, c, d
Which of the following statements correctly describe the fundamental data structures in Pandas? a. A Series is a 1D ordered data structure where every element has an index/label, and typically contains a single data type . b. A DataFrame is a 2D data structure for tabular data, comparable to a spreadsheet or an SQL table . c. A DataFrame can be thought of as multiple Series (columns) that share the same index . d. Unlike NumPy arrays, a DataFrame can support different data types in its columns .
a, b, c, d
Consider a Pandas DataFrame df with a custom index like Index([‘a’, ‘b’, ‘c’], dtype=’object’). Which of the following methods would reset the index to the default integer indexing (from 0 to n-1) and avoid adding the old index as a new column? a. df.reset_index() b. df.reset_index(inplace=True) c. df.reset_index(drop=True) d. df.set_index(range(len(df)))
c
When indexing and slicing a Pandas DataFrame, loc and iloc are commonly used. Which of the following statements correctly distinguish loc and iloc? a. df.loc selects a row using its label . b. df.iloc selects a row using its integer position . c. When slicing rows using labels with df.loc, the upper bound is inclusive . d. When slicing rows using integer indices with df.iloc, the upper bound is inclusive .
a, b, c (d is incorrect, iloc upper bound is exclusive)