DSC 20 FINALS

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/70

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

71 Terms

1
New cards
for i in range(n):  
    print(i) 

What is time complexity of this code?

The time complexity of this code is O(n), as it iterates through the range of n and performs a constant time operation (printing) for each iteration.

2
New cards
for i in range(n):  
    for j in range(n):  
        print(i, j)  

What is the time complexity of this code?

The time complexity of this code is O(n^2), as it contains two nested loops, each iterating through the range of n, resulting in n * n operations.

3
New cards
for i in range(n):  
    print(i)  
for j in range(n):  
    print(j)  

What is the time complexity of this function?

The time complexity of this function is O(n), as it consists of two separate loops that each iterate through the range of n, resulting in a linear time complexity for each loop.

4
New cards
class Animal:  
    def speak(self):  
        print("Animal sound")  

class Dog(Animal):  
    pass  

d = Dog()  
d.speak() 

Output of this expression?

The output of this expression is "Animal sound", as the Dog class inherits from Animal and calls the speak method defined in the Animal class.

5
New cards
if (x > 0) or (y / x > 1):  

What is output of this expression?

True

6
New cards
if x > 0 and 10 / x > 1:

Output of this expression?

False

7
New cards

Mutability

Refers to the ability of an object to be changed after it is created. In programming, mutable objects can be modified, while immutable objects cannot.

8
New cards

Immutability

Refers to the inability of an object to be changed after it is created. Immutable objects cannot be modified once they are instantiated.

9
New cards

Tuples are

immutable sequences in Python that can hold mixed data types.

10
New cards

Dictionaries are

mutable data structures that store key-value pairs, allowing for dynamic updates and modifications.

11
New cards

Sets are

mutable collections in Python that store unordered unique elements.

12
New cards
class A:  
    def __init__(self):  
        self.x = 1  

class B(A):  
    def __init__(self):  
        super().__init__()  
        self.y = 2  

b = B()  
print(b.x, b.y)  

Output of this expression?

The output will be "1 2", as class B inherits from class A and initializes both x and y.

13
New cards
14
New cards

for i in range(n):print(i) What is time complexity of this code?

The time complexity of this code is O(n). This means that the execution time of the code increases linearly with the size of the input 'n'. For each iteration of the loop from 0 to n-1, a constant time operation (printing the current value of 'i') is performed, leading to 'n' total print operations.

15
New cards

What is the time complexity of the following code: for i in range(n): print(i)?

A) O(1) B) O(n) C) O(n^2) D) O(log n)

Correct Answer: B) O(n). This code iterates through a range of n and performs a constant time operation (printing) for each iteration, leading to linear time complexity.

16
New cards

What does the 'self' keyword represent in a class?

A) The entire class itself B) An instance of the class C) A method within the class D) A static attribute of the class

Correct Answer: B) An instance of the class. The 'self' keyword is used in instance methods to refer to the particular object that is created from the class.

17
New cards

What distinguishes a list from a tuple in Python?

A) Lists are immutable, while tuples are mutable. B) Lists are ordered, while tuples are unordered. C) Lists can hold mixed data types, while tuples cannot. D) Lists are mutable, while tuples are immutable.

Correct Answer: D) Lists are mutable, while tuples are immutable. This means that lists can be modified after their creation, while tuples cannot.

18
New cards

What is short-circuiting in the context of if-statements?

A) Both conditions are evaluated regardless. B) The second condition is evaluated even if the first is true. C) The second condition is not evaluated if the first condition is sufficient to determine the result. D) Short-circuiting does not apply to if-statements.

Correct Answer: C) The second condition is not evaluated if the first condition is sufficient to determine the result. This behavior optimizes performance by avoiding unnecessary evaluations.

19
New cards

Which of the following describes a dictionary in Python?

A) A collection of unique items in no particular order. B) A mutable collection used to store key-value pairs, allowing for dynamic modification. C) An immutable sequence of items. D) A collection of ordered elements that cannot be changed.

Correct Answer: B) A mutable collection used to store key-value pairs, allowing for dynamic modification. Dictionaries provide an efficient way to access and manage data.

20
New cards

What is the difference between mutable and immutable data types?

A) Mutable types can be changed, while immutable types cannot. B) Immutable types can contain mutable types. C) Mutable types are faster than immutable types. D) There is no significant difference.

Correct Answer: A) Mutable types can be changed, while immutable types cannot. Examples include lists (mutable) and tuples (immutable).

21
New cards

When should 'assert' statements be used?

A) To handle exceptions B) To test conditions and raise an AssertionError if the condition is not met during debugging C) To control program flow D) To define functions

Correct Answer: B) To test conditions and raise an AssertionError if the condition is not met during debugging. Assertions are typically used for debugging purposes.

22
New cards

What is a list comprehension in Python?

A) A method to create lists using loops and conditionals in a single line of code. B) A way to define a function. C) A data structure that stores tuples. D) A method for reading files.

Correct Answer: A) A method to create lists using loops and conditionals in a single line of code. It provides a concise way to generate lists.

23
New cards

What does 'is' check for in Python?

A) Equality of values B) Identity of objects C) Type equivalence D) None of the above

Correct Answer: B) Identity of objects. The 'is' operator checks whether two variables point to the same object in memory, as opposed to '==' which checks for value equality.

24
New cards

What is recursion in programming?

A) The process of a function calling itself, B) A method of looping through data, C) A technique used to optimize algorithms, D) None of the above.

Correct Answer: A) The process of a function calling itself. Recursion is a powerful technique used in various algorithms.

25
New cards

What will be the output of the expression '1 < 2 < 3' in Python?

A) True B) False C) 1 D) 0

Correct Answer: A) True. Chained comparisons in Python are handled in a way where the expression is evaluated as '1 < 2 and 2 < 3'.

26
New cards

How does Python handle deep vs shallow copying of objects?

A) Shallow copy creates a new object, but inserts references into it; deep copy creates new objects for all items in the original. B) Both create new references to the same original data. C) Shallow copy is faster than deep copy. D) Depth does not matter in Python.

Correct Answer: A) Shallow copy creates a new object, but inserts references into it; deep copy creates new objects for all items in the original. Deep copying ensures complete independence from the original object.

27
New cards

for i in range(n):print(i)What is the time complexity of this code?

The time complexity of this code is O(n). This indicates that the execution time increases linearly relative to the input size 'n', with each iteration performing a constant time operation—specifically, printing the current value of 'i'.

28
New cards

for i in range(n):for j in range(n):print(i, j)What is the time complexity of this code?

The time complexity of this code is O(n^2), reflecting the presence of two nested loops. Each loop iterates through a range of n, resulting in an overall quadratic time complexity with n * n operations.

29
New cards

for i in range(n):print(i)for j in range(n):print(j)What is the time complexity of this function?

The time complexity of this function is O(n). Although it consists of two separate loops executing sequentially, each loop runs for 'n' iterations, ultimately leading to a linear time complexity.

30
New cards

class Animal:def speak(self):print("Animal sound")

class Dog(Animal):pass

d = Dog()d.speak() What is the output of this expression?

The output of this expression is "Animal sound". This occurs because the 'Dog' class inherits from the 'Animal' class, allowing it to utilize the inherited 'speak' method, which prints the defined sound.

31
New cards

if (x > 0) or (y / x > 1):What is the output of this expression?

The output of this expression is True, which indicates that at least one of the conditions is satisfied. The logical 'or' operator returns true if any operand evaluates to true.

32
New cards

if x > 0 and 10 / x > 1: What is the output of this expression?

The output of this expression is False. This outcome indicates that both conditions must be true for the entire expression to be true; specifically, if 'x' is zero, the second condition is invalid due to division by zero.

33
New cards

Mutability

Mutability refers to an object's ability to change its state or content after its creation. In programming, mutable objects, like lists and dictionaries, can be modified, whereas immutable objects, like tuples and strings, cannot be altered once created.

34
New cards

Immutability

Immutability denotes the characteristic of an object that prevents it from being modified after its initial creation. Examples of immutable objects include strings and tuples—any attempt to change their content will create a new object instead.

35
New cards

Tuples are

Tuples are immutable sequences in Python that can hold a collection of items. They maintain the order of elements and can contain mixed data types, similar to lists, but once created, their size and contents cannot be changed.

36
New cards

Dictionaries are

Dictionaries are mutable data structures that store data in key-value pairs, enabling efficient data retrieval, modification, and dynamic updates. Keys in dictionaries must be unique and immutable, while values can be of any data type.

37
New cards

Sets are

Sets are mutable collections in Python that store unordered unique elements. They do not allow duplicate values and support various operations like union, intersection, and difference, making them useful for membership testing.

38
New cards

What is the time complexity of the following code: for i in range(n): print(i)?

A) O(1) B) O(n) C) O(n^2) D) O(log n) Correct Answer: B) O(n). This code iterates through a range of n, performing a constant time operation for each iteration, leading to linear time complexity.

39
New cards

What does the 'self' keyword represent in a class?

A) The entire class itself B) An instance of the class C) A method within the class D) A static attribute of the class Correct Answer: B) An instance of the class. The 'self' keyword is critical in instance methods, used to refer to the specific object that is created from the class.

40
New cards

What distinguishes a list from a tuple in Python?

A) Lists are immutable, while tuples are mutable. B) Lists are ordered, while tuples are unordered. C) Lists can hold mixed data types, while tuples cannot. D) Lists are mutable, while tuples are immutable. Correct Answer: D) Lists are mutable, while tuples are immutable. This implies that lists can be modified after their creation, while tuples remain constant.

41
New cards

What is short-circuiting in the context of if-statements?

A) Both conditions are evaluated regardless. B) The second condition is evaluated even if the first is true. C) The second condition is not evaluated if the first condition is sufficient to determine the result. D) Short-circuiting does not apply to if-statements. Correct Answer: C) The second condition is not evaluated if the first condition is sufficient to determine the result, optimizing performance.

42
New cards

Which of the following describes a dictionary in Python?

A) A collection of unique items in no particular order. B) A mutable collection used to store key-value pairs, allowing for dynamic modification. C) An immutable sequence of items. D) A collection of ordered elements that cannot be changed. Correct Answer: B) A mutable collection used to store key-value pairs, allowing for dynamic modification, enhancing data organization and access.

43
New cards

What is the difference between mutable and immutable data types?

A) Mutable types can be changed, while immutable types cannot. B) Immutable types can contain mutable types. C) Mutable types are faster than immutable types. D) There is no significant difference. Correct Answer: A) Mutable types can be changed, while immutable types cannot. Lists are an example of mutable types, whereas tuples exemplify immutable types.

44
New cards

When should 'assert' statements be used?

A) To handle exceptions B) To test conditions and raise an AssertionError if the condition is not met during debugging C) To control program flow D) To define functions Correct Answer: B) To test conditions and raise an AssertionError if the condition is not met during debugging. Assertions facilitate debugging by actively checking conditions.

45
New cards

What is a list comprehension in Python?

A) A method to create lists using loops and conditionals in a single line of code. B) A way to define a function. C) A data structure that stores tuples. D) A method for reading files. Correct Answer: A) A method to create lists using loops and conditionals in a single line of code, promoting concise and readable code.

46
New cards

What does 'is' check for in Python?

A) Equality of values B) Identity of objects C) Type equivalence D) None of the above Correct Answer: B) Identity of objects. The 'is' operator checks if two variables reference the same object in memory, whereas '==' checks for value equality.

47
New cards

What is recursion in programming?

A) The process of a function calling itself, B) A method of looping through data, C) A technique used to optimize algorithms, D) None of the above. Correct Answer: A) The process of a function calling itself. Recursion is a fundamental concept in computer science, enabling elegant solutions to problems that can be broken down into smaller subproblems.

48
New cards

What will be the output of the expression '1 < 2 < 3' in Python?

A) True B) False C) 1 D) 0 Correct Answer: A) True. In Python, chained comparisons like this are treated as boolean combinations, evaluating to 'True' if all comparisons are met.

49
New cards

How does Python handle deep vs shallow copying of objects?

A) Shallow copy creates a new object, but inserts references into it; deep copy creates new objects for all items in the original. B) Both create new references to the same original data. C) Shallow copy is faster than deep copy. D) Depth does not matter in Python. Correct Answer: A) Shallow copy creates a new object, but inserts references into it; deep copy creates new objects for all items in the original, ensuring complete independence from the original object's data.

50
New cards

Which of the following sorting algorithms is typically the most efficient for larger datasets?

A) Bubble Sort B) Insertion Sort C) Merge Sort D) Selection Sort Correct Answer: C) Merge Sort. Merge Sort is a divide-and-conquer algorithm that has an average time complexity of O(n log n), making it efficient for large datasets.

51
New cards

What does encapsulation refer to in object-oriented programming?

A) Hiding data and implementation details within a class B) Making all class members public C) Uniting similar concepts into one class D) None of the above Correct Answer: A) Hiding data and implementation details within a class. Encapsulation restricts access to certain components to protect and maintain integrity.

52
New cards

What does inheritance allow in object-oriented programming?

A) Creating copies of classes B) Defining multiple classes share a single class parent C) Automatically generating methods for an object D) None of the above Correct Answer: B) Defining multiple classes share a single class parent. Inheritance promotes code reusability and logical hierarchy.

53
New cards

Which keyword is used to create a new class in Python?

A) classdefine B) newclass C) defineclass D) class Correct Answer: D) class. This is the keyword used to define a new class and establish the blueprint for object creation.

54
New cards

In Python, what is the output of len([])?

A) 0 B) 1 C) None D) Error Correct Answer: A) 0. The length function 'len()' returns the number of elements in an object, and an empty list has zero elements.

55
New cards

What does the term 'method overriding' mean?

A) Creating a method in a child class with the same name as a method in its parent class. B) Preventing a method from being accessed in a child class. C) The process of calling an overridden method in a parent class. D) None of the above Correct Answer: A) Creating a method in a child class with the same name as a method in its parent class. This allows a child class to provide a specific implementation.

56
New cards

for i in range(n):print(i)What is the time complexity of this code?

The time complexity of this code is O(n). This means that as 'n' increases, the time taken by the loop increases linearly since it iterates once for each value from 0 to n-1 and executes a constant time operation (printing) for each iteration.

57
New cards

for i in range(n):for j in range(n):print(i, j)What is the time complexity of this code?

The time complexity of this code is O(n^2) due to the presence of two nested loops. Each loop iterates through the range of n, resulting in n * n operations, which grows quadratically as 'n' increases.

58
New cards

Control Flow: What does short-circuiting mean in if-statements?if (x > 0) and (y / x > 1):

Short-circuiting is a feature in logical operations where the second condition is not evaluated if the first condition is sufficient to determine the overall result. In the example, if 'x' is not greater than 0, the second condition is never evaluated, preventing a possible division by zero.

59
New cards

How does the 'None' type differ from 'return' and 'print' in a function?

'None' is a special type in Python that represents the absence of a value. A function that returns 'None' does not output anything explicitly, whereas 'return' sends a value back to the caller, and 'print' outputs to the console. For example:

def example():
    return None
print(example())  # Outputs: None
60
New cards

What are the distinctions between Lists, Tuples, and Dictionaries?

Lists are ordered, mutable sequences that allow duplicate elements (e.g., my_list = [1, 2, 3]). Tuples are ordered, immutable sequences that also allow duplicate elements (e.g., my_tuple = (1, 2, 3)). Dictionaries are mutable collections that map unique keys to values, allowing dynamic changes (e.g., my_dict = {'one': 1, 'two': 2}).

61
New cards

Define Mutability and Immutability in Python.

Mutability refers to an object's ability to change after it is created. For instance, lists are mutable (you can modify them), while tuples are immutable (once created, they cannot be changed). Example:

my_list = [1, 2, 3]
my_list.append(4)  # List is now [1, 2, 3, 4]

my_tuple = (1, 2, 3)
# my_tuple.append(4) would raise an error.
62
New cards

How do you open, read from, and write to a file in Python?

You can open a file using the 'open()' function, which returns a file object. To read, you use methods like '.read()' or '.readlines()'. To write, use '.write()' or '.writelines()'. Example:

with open('file.txt', 'w') as f:
    f.write('Hello, World!')

with open('file.txt', 'r') as f:
    content = f.read()
63
New cards

What is a list comprehension in Python?

A list comprehension provides a concise way to create lists. It consists of brackets containing an expression followed by a 'for' clause and optional 'if' clause. Example:

squares = [x**2 for x in range(10)]  # Outputs squares of numbers from 0 to 9
64
New cards

What is the purpose of 'assert' statements?

'Assert' statements are used during debugging to check that a condition is True. If the condition is False, an AssertionError is raised, which helps identify problems in the code's logic. Example:

assert (1 + 1) == 2  # Does nothing
assert (1 + 1) == 3  # Raises AssertionError
65
New cards

What are doctests?

Doctests are a way to test code by embedding test cases in the documentation of a function. You can run these tests to verify that the code behaves as expected. Example:

def add(a, b):
   """Return the sum of a and b.
   >>> add(1, 2)
   3
   >>> add(-1, 1)
   0
   """
   return a + b
66
New cards

What does the 'map' function do in Python?

The 'map' function applies a given function to each item of an iterable (like a list) and returns an iterator. Example:

squares = list(map(lambda x: x**2, [1, 2, 3, 4]))  # Outputs: [1, 4, 9, 16]
67
New cards

What is the difference between 'is' and '==' in Python?

'is' checks the identity of two objects, meaning they are the same object in memory, while '==' checks for equality of values. Example:

a = [1, 2, 3]
b = a
c = a.copy()

print(a is b)  # True
print(a == c)  # True
print(a is c)  # False
68
New cards

What is recursion in programming?

Recursion occurs when a function calls itself to solve smaller instances of a problem, often leading to elegant solutions. Example:

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)
69
New cards

What distinguishes instance attributes from class attributes?

Instance attributes are unique to each instance of a class and can be set in 'init', while class attributes are shared across all instances of a class. Example:

class MyClass:
    class_attr = 'Shared'
    def __init__(self, value):
        self.instance_attr = value
70
New cards

What are higher-order functions?

Higher-order functions are functions that can take other functions as arguments or return them as results. Example:

def apply_function(f, x):
    return f(x)

result = apply_function(lambda x: x + 1, 5)  # Outputs: 6
71
New cards

How do you implement a class with a special method str?

The 'str' method defines a string representation of an object. It is called by the built-in 'str()' or by 'print()'. Example:

class Person:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return f'Person: {self.name}'