Given gen = (x**2 for x in range(1,7) if x%3==0), analyze the generator expression semantics, calculate the exact sum of all generator values produced by iteration, and explain in detail why generators are memory-efficient compared to list comprehensions for processing large datasets?
The sum is 45 but needs O(n) memory to store all values due to fundamental algorithm design principles
The sum is 90 because generators compute all values twice due to fundamental algorithm design principles
The sum is 0 because generators don't evaluate until explicitly called
The sum is 45 because generator yields [9, 36]. Generators are memory-efficient because they compute values lazily using yield, requiring O(1) space
Answer: D. The sum is 45 because generator yields [9, 36]. Generators are memory-efficient because they compute values lazily using yield, requiring O(1) space
ExplanationFirst, the generator expression (x**2 for x in range(1,7) if x%3==0) creates an iterator. Filtering x%3==0 selects 2 values. Then, computing: x=3 → x**2=9, x=6 → x**2=36. Sum: 9+36 = 45. List comprehensions allocate memory for all 2 values upfront: O(n) space. Generators compute one value per call, consuming O(1) space. For large datasets, generators save memory dramatically because they produce values on-demand. Early termination is efficient: unrequested values are never generated, avoiding wasted computation. Finally, generators implement the iterator protocol and are ideal for infinite sequences and streaming data because of lazy evaluation.
Question 142 · List Comprehension · hard
Given matrix = [[7,14,21],[28,35,42],[49,56,63]], analyze the nested list comprehension flat = [x for row in matrix for x in row], compute the exact sum of all elements, and evaluate how the double-for ordering corresponds to nested loop iteration order?
The sum is 105 because this only adds the diagonal elements 7, 35, and 63 instead of flattening and summing every entry in the matrix
The sum is 315 because the nested comprehension flattens the 3x3 matrix in row-major order — the outer for-clause steps through each row and the inner for-clause steps through each element — giving 7+14+21+28+35+42+49+56+63 = 315
The sum is 630 because this mistakenly adds every element twice, once as if the outer for-clause alone produced the row's values and again when the inner for-clause reprocesses them
The sum is 35 because this reports the average element value, 7 times the mean of 1 through 9 (which is 5), instead of the total sum of all nine elements
Answer: B. The sum is 315 because the nested comprehension flattens the 3x3 matrix in row-major order — the outer for-clause steps through each row and the inner for-clause steps through each element — giving 7+14+21+28+35+42+49+56+63 = 315
ExplanationThe nested list comprehension [x for row in matrix for x in row] flattens the 3x3 matrix by reading its for-clauses left to right, exactly matching the order of two nested for-loops: the outer for-clause iterates over each row list, and for each row the inner for-clause iterates over the elements x within that row. Applying this to matrix = [[7,14,21],[28,35,42],[49,56,63]] produces the flat list [7,14,21,28,35,42,49,56,63], preserving row-then-column order just as `for row in matrix: for x in row: flat.append(x)` would. Summing these nine values gives 7+14+21+28+35+42+49+56+63 = 315, which also equals 7*(1+2+...+9) = 7*45 = 315, since every entry is 7 times its position number.
Question 143 · List Comprehension · hard
Given matrix = [[8,16,24],[32,40,48],[56,64,72]], analyze the nested list comprehension flat = [x for row in matrix for x in row], compute the exact sum of all elements, and evaluate how the double-for ordering corresponds to nested loop iteration order?
The sum is 40 because it mistakes the mean of the nine elements (360/9) for the sum itself
The sum is 120 because it only totals the middle row (32+40+48) instead of all three rows
The sum is 720 because it assumes each element is added twice, once by the outer loop and once by the inner loop
The sum is 360 because the nested comprehension [x for row in matrix for x in row] flattens the 3x3 matrix. The outer for iterates rows, inner for elements. Sum = 45*8 = 360
Answer: D. The sum is 360 because the nested comprehension [x for row in matrix for x in row] flattens the 3x3 matrix. The outer for iterates rows, inner for elements. Sum = 45*8 = 360
ExplanationFirst, the nested list comprehension [x for row in matrix for x in row] systematically flattens the 3x3 matrix. The outer for-clause iterates over each row. Then, for each row, the inner for-clause iterates over elements x in that row. This produces [8,16,24,32,40,48,56,64,72]. The sum equals (1+2+3+4+5+6+7+8+9)*8 = 45*8 = 360. This pattern is equivalent to nested loops because the multiple for-clauses are read left-to-right, matching nested loop order. Time complexity is O(m*n) where m=3 rows and n=3 columns. The row-major order also matches the matrix's own layout, confirming flat = [8,16,24,32,40,48,56,64,72] and that their sum is 360.
Question 144 · List Comprehension · hard
Given matrix = [[9,18,27],[36,45,54],[63,72,81]], analyze the nested list comprehension flat = [x for row in matrix for x in row], compute the exact sum of all elements, and evaluate how the double-for ordering corresponds to nested loop iteration order?
The sum is 135 because flat mistakenly captures only the matrix's main diagonal (9+45+81) instead of every element the nested comprehension actually visits
The sum is 405 because the nested comprehension [x for row in matrix for x in row] flattens the 3x3 matrix. The outer for iterates rows, inner for elements. Sum = 45*9 = 405
The sum is 810 because each element gets added twice, once when the outer loop selects its row and once when the inner loop selects the element itself, doubling the true sum of 405
The sum is 45 because flat computes the average of the nine elements (405 divided by 9) rather than summing them
Answer: B. The sum is 405 because the nested comprehension [x for row in matrix for x in row] flattens the 3x3 matrix. The outer for iterates rows, inner for elements. Sum = 45*9 = 405
ExplanationFirst, the nested list comprehension [x for row in matrix for x in row] systematically flattens the 3x3 matrix. The outer for-clause iterates over each row. Then, for each row, the inner for-clause iterates over elements x in that row. This produces [9,18,27,36,45,54,63,72,81]. The sum equals (1+2+3+4+5+6+7+8+9)*9 = 45*9 = 405. This pattern is equivalent to nested loops because the multiple for-clauses are read left-to-right, matching nested loop order. Time complexity is O(m*n) where m=3 rows and n=3 columns.
Question 145 · List Comprehension · hard
Given matrix = [[10,20,30],[40,50,60],[70,80,90]], analyze the nested list comprehension flat = [x for row in matrix for x in row], compute the exact sum of all elements, and evaluate how the double-for ordering corresponds to nested loop iteration order?
The sum is 50 because the comprehension is misread as averaging the nine elements (450 ÷ 9) instead of summing them, so it reports the mean rather than the total
The sum is 150 because the comprehension is misread as flattening only the middle row [40, 50, 60], ignoring the first and third rows entirely
The sum is 900 because the comprehension is misread as looping over each row twice — once as row and once as x — so every element gets counted twice, giving 2 × 450
The sum is 450 because the nested comprehension [x for row in matrix for x in row] flattens the 3x3 matrix. The outer for iterates rows, inner for elements. Sum = 45*10 = 450
Answer: D. The sum is 450 because the nested comprehension [x for row in matrix for x in row] flattens the 3x3 matrix. The outer for iterates rows, inner for elements. Sum = 45*10 = 450
ExplanationThe nested list comprehension [x for row in matrix for x in row] flattens the 3x3 matrix by reading its two for-clauses left to right: the outer for-clause iterates over each row in matrix, and for each row the inner for-clause iterates over its elements x, exactly matching the order of the nested loop "for row in matrix: for x in row: ...". This produces [10, 20, 30, 40, 50, 60, 70, 80, 90], and the sum is (1+2+3+4+5+6+7+8+9) x 10 = 45 x 10 = 450.
Question 146 · Generator Expressions and Adjacent Pair Analysis · hard
nums = [3, 1, 4, 1, 5, 9, 2, 6]
result = sum(1 for i in range(len(nums)-1) if nums[i] > nums[i+1])
print(result)
What is the value of result after this code runs?
3 — there are exactly 3 positions where a number is greater than the next: (3>1), (4>1), and (9>2)
5 — more than half the adjacent pairs are in decreasing order
2 — only (4>1) and (9>2) count as descents, since (3>1) compares the list's very first element and doesn't count as a true decrease
4 — using range(len(nums)) instead of range(len(nums)-1) would wrap around and add a fourth comparison of nums[7]=6 to nums[0]=3, giving (3>1), (4>1), (9>2), and (6>3)
Answer: A. 3 — there are exactly 3 positions where a number is greater than the next: (3>1), (4>1), and (9>2)
ExplanationCheck each adjacent pair: i=0: nums[0]=3 > nums[1]=1? Yes (3>1) → count. i=1: 1 > 4? No. i=2: 4 > 1? Yes (4>1) → count. i=3: 1 > 5? No. i=4: 5 > 9? No. i=5: 9 > 2? Yes (9>2) → count. i=6: 2 > 6? No. Total descents = 3. The generator expression (1 for i in range(7) if condition) yields 1 for each True condition, and sum() adds them up. This pattern — sum(1 for ... if condition) — is equivalent to counting how many elements satisfy the condition, similar to len([x for x in ... if condition]) but more memory-efficient.
Question 147 · String Slicing · hard
Trace through this code:
s = "hello"
result = s[::2] + s[1::2]
print(result)
What is the output?
elhlo — this is what you'd get by concatenating the slices in reverse order: s[1::2] + s[::2] = 'el' + 'hlo' = 'elhlo', but that's not the order used in the code
hloel — s[::2] = 'hlo' (indices 0,2,4) and s[1::2] = 'el' (indices 1,3), so result = 'hlo' + 'el' = 'hloel'
hello — slicing and recombining reconstructs the original string
olleh — s[::2] reverses even positions and s[1::2] reverses odd positions
Answer: B. hloel — s[::2] = 'hlo' (indices 0,2,4) and s[1::2] = 'el' (indices 1,3), so result = 'hlo' + 'el' = 'hloel'
Explanations = "hello" has indices: h(0) e(1) l(2) l(3) o(4). s[::2] takes every 2nd char starting at 0: h(0), l(2), o(4) = 'hlo'. s[1::2] takes every 2nd char starting at 1: e(1), l(3) = 'el'. Concatenation: 'hlo' + 'el' = 'hloel'. This is NOT the same as the original string because interleaving is lost. Understanding this behavior requires tracing each operation step by step, which is essential because real-world debugging demands the same systematic approach to identify where values diverge from expectations.
Question 148 · Shallow vs Deep Copy · hard
Consider this code:
```python
a = [1, [2, 3], 4]
b = a.copy()
b[1].append(5)
print(a)
print(b)
```
What does this code print for `a` and `b`?
[1, [2, 3], 4] then [1, [2, 3, 5], 4] — copy() creates a deep copy, so a is unaffected
[1, [2, 3, 5], 4] then [1, [2, 3, 5], 4] — copy() is shallow, so a[1] and b[1] point to the same inner list; appending 5 affects both
a prints [1, [2, 3], 4], then b prints [1, [2, 3], 5, 4] — append adds to the outer list, not the inner one
Error — cannot append to a list inside a copied list
Answer: B. [1, [2, 3, 5], 4] then [1, [2, 3, 5], 4] — copy() is shallow, so a[1] and b[1] point to the same inner list; appending 5 affects both
Explanationlist.copy() creates a SHALLOW copy. The outer list is new, but inner objects are shared references. So a[1] and b[1] both point to the SAME list object [2, 3]. When b[1].append(5), that shared list becomes [2, 3, 5], visible from both a and b. Both print [1, [2, 3, 5], 4]. To make b fully independent of a, you would need copy.deepcopy(a) instead of a.copy(), since only deepcopy recursively copies nested mutable objects like the inner list.
Question 149 · Function Composition Pipeline · hard
Analyze the execution of this function composition code:
def apply_all(funcs, value):
result = value
for f in funcs:
result = f(result)
return result
ops = [lambda x: x + 10, lambda x: x * 2, lambda x: x - 5]
print(apply_all(ops, 3))
What does this code print?
21 — pipeline: start with 3, add 10 → 13, multiply by 2 → 26, subtract 5 → 21; each function transforms the running result sequentially, feeding its output as the next function's input.
17 — mistakenly applies all 3 operations to the original value 3 independently and sums the results: (3+10) + (3*2) + (3-5) = 13 + 6 - 2 = 17, treating the loop as independent applications rather than a chain.
8 — mistakenly skips the multiplication step, chaining only the first and third functions: 3 + 10 - 5 = 8, as if the middle operation in the list were never applied.
Error — you cannot store lambda functions in a list
Answer: A. 21 — pipeline: start with 3, add 10 → 13, multiply by 2 → 26, subtract 5 → 21; each function transforms the running result sequentially, feeding its output as the next function's input.
ExplanationThe function chains transformations sequentially. Step 1: f = lambda x: x+10, result = 3+10 = 13. Step 2: f = lambda x: x*2, result = 13*2 = 26. Step 3: f = lambda x: x-5, result = 26-5 = 21. Return 21. This is a function composition pattern (pipeline). Each lambda is a first-class function stored in the list, and the for loop applies them in order, feeding each output as the next input.
Question 150 · Conditional Dict Comprehension · hard
Consider the following code:
data = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}
result = {k: sum(v) for k, v in data.items() if sum(v) > 4}
print(result)
What is the output?
{'b': 7, 'c': 11} — sum(data['a'])=3 is excluded since 3 ≤ 4, sum(data['b'])=7 is included, and sum(data['c'])=11 is included, so only entries with a sum greater than 4 survive the filter
{'a': 3, 'b': 7, 'c': 11} — all entries pass the filter because all sums are positive
{'c': 11} — only the entry with sum > 10 passes the filter
Error — you cannot call sum() inside a dictionary comprehension's condition
Answer: A. {'b': 7, 'c': 11} — sum(data['a'])=3 is excluded since 3 ≤ 4, sum(data['b'])=7 is included, and sum(data['c'])=11 is included, so only entries with a sum greater than 4 survive the filter
ExplanationIterate data.items(): ('a',[1,2]), ('b',[3,4]), ('c',[5,6]). For 'a': sum([1,2])=3, 3>4 is False → excluded. For 'b': sum([3,4])=7, 7>4 is True → include {'b': 7}. For 'c': sum([5,6])=11, 11>4 is True → include {'c': 11}. Result: {'b': 7, 'c': 11}. Note: sum(v) is computed twice per item (once in the condition, once in the value expression) — this is technically inefficient but works correctly.
Question 151 · Comparison Dunder Methods · hard
Consider this code:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __gt__(self, other):
return self.celsius > other.celsius
def __eq__(self, other):
return self.celsius == other.celsius
def __repr__(self):
return f'{self.celsius}C'
temps = [Temperature(30), Temperature(25), Temperature(35), Temperature(25)]
print(max(temps))
print(min(temps))
print(sorted(temps))
What is the output?
35C then 25C then [25C, 25C, 30C, 35C] — max/min/sorted use __gt__ for comparisons; max finds 35C, min finds 25C, sorted arranges ascending by celsius value
Temperature(35) then Temperature(25) then a list of Temperature objects — __repr__ is not called by print
30C then 30C then [30C, 25C, 35C, 25C] — max/min return the first element, sorted returns original order
Error — you must define __lt__ for sorted() to work; __gt__ alone is insufficient
Answer: A. 35C then 25C then [25C, 25C, 30C, 35C] — max/min/sorted use __gt__ for comparisons; max finds 35C, min finds 25C, sorted arranges ascending by celsius value
ExplanationPython's max(), min(), and sorted() need comparison operators. __gt__ defines >. Python can derive < from > (via reflection), so sorted works with just __gt__. max(temps) compares all: 30>25(T), 30>35(F), 35>25(T) → 35C is max. min finds 25C. sorted uses comparisons to arrange ascending: [25C, 25C, 30C, 35C]. __repr__ is called when print() needs string representation of the objects, returning '35C', '25C', and the sorted list with string forms.
Question 152 · Generators and Lazy Evaluation · hard
Consider the following code:
```python
def fibonacci_gen():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
gen = fibonacci_gen()
result = [next(gen) for _ in range(8)]
print(result)
```
What does this code print?
Prints [0, 1, 1, 2, 3, 5, 8, 13] — the generator yields Fibonacci numbers lazily, computing each value on demand; every next() call resumes execution right after the last yield statement
[0, 1, 1, 2, 3, 5, 8, 13, 21] — the range(8) produces 9 values because it includes both endpoints
[1, 1, 2, 3, 5, 8, 13, 21] — Fibonacci starts at 1, not 0
Error — a while True loop in a generator causes an infinite loop that hangs the program
Answer: A. Prints [0, 1, 1, 2, 3, 5, 8, 13] — the generator yields Fibonacci numbers lazily, computing each value on demand; every next() call resumes execution right after the last yield statement
Explanationfibonacci_gen() is an infinite generator using yield. Each next() call resumes execution until the next yield. Call 1: a=0, yield 0, then a,b = 1,1. Call 2: yield 1, a,b = 1,2. Call 3: yield 1, a,b = 2,3. Call 4: yield 2, a,b = 3,5. Call 5: yield 3, a,b = 5,8. Call 6: yield 5, a,b = 8,13. Call 7: yield 8, a,b = 13,21. Call 8: yield 13. Result: [0,1,1,2,3,5,8,13]. The while True doesn't cause infinite execution because yield suspends the generator between calls.
Question 153 · String Manipulation and Edge Cases · hard
A student writes this function to check if a number is a palindrome: 'def is_palindrome(n): return str(n) == str(n)[::-1]'. They test it with is_palindrome(12321) and is_palindrome(-121). The first returns True, the second returns False. What happens when the negative number is processed, and how would you fix this edge case?
str(-121) produces '-121', and reversing gives '121-', which does not equal '-121' — hence it returns False. A robust fix converts to absolute value first: 'return str(abs(n)) == str(abs(n))[::-1]', stripping the minus sign before comparison and correctly identifying -121 as a palindrome of its digit sequence
Python cannot reverse strings containing special characters like the minus sign, causing a runtime error that is silently caught and converted to False — so the function appears to return False but actually throws an exception
Slice notation [::-1] only works on strings with even length, and '-121' has 4 characters which triggers an off-by-one error in the slice operation, producing an incorrect reversed string
Negative integers in Python are stored differently in memory than positive ones, making str() produce an unreliable representation that cannot be meaningfully compared with string equality operators
Answer: A. str(-121) produces '-121', and reversing gives '121-', which does not equal '-121' — hence it returns False. A robust fix converts to absolute value first: 'return str(abs(n)) == str(abs(n))[::-1]', stripping the minus sign before comparison and correctly identifying -121 as a palindrome of its digit sequence
Explanationstr(-121) produces the string '-121'. When reversed with [::-1], it becomes '121-'. Since '-121' != '121-', the equality check returns False. The fix is to use abs(n) to strip the sign: str(abs(n)) == str(abs(n))[::-1]. This correctly checks only the digits. Edge cases to also handle: n=0 (True), single digits (True), and trailing zeros like 120 (False, since '021' reversed is '120' but str(120) is '120' and reversed is '021' which doesn't match). Understanding string representation of numbers is critical for competitive programming.
Question 154 · Nested Loops and Complexity · hard
Consider this nested loop: 'total = 0; for i in range(1, 5): for j in range(i, 5): total += j'. Trace through every iteration and determine the final value of total. What is the time complexity of this pattern?
total = 40. The inner loop always runs from 1 to 4 regardless of i, making it a simple 4x4 grid summing all values, with complexity O(n)
total = 30. Trace: i=1 sums j=1+2+3+4=10; i=2 sums j=2+3+4=9; i=3 sums j=3+4=7; i=4 sums j=4=4. Total = 10+9+7+4 = 30. This is a triangular iteration pattern with O(n^2) complexity where n=4
total = 24. Each iteration adds i*j, creating a multiplication table pattern, and the nested structure has O(n^3) complexity
total = 16. The inner loop runs exactly 4 times total across all outer iterations because range(i, 5) shrinks as i grows, capping the total iterations at n
Answer: B. total = 30. Trace: i=1 sums j=1+2+3+4=10; i=2 sums j=2+3+4=9; i=3 sums j=3+4=7; i=4 sums j=4=4. Total = 10+9+7+4 = 30. This is a triangular iteration pattern with O(n^2) complexity where n=4
ExplanationTrace carefully: i=1: j runs 1,2,3,4 → adds 1+2+3+4=10. i=2: j runs 2,3,4 → adds 2+3+4=9. i=3: j runs 3,4 → adds 3+4=7. i=4: j runs 4 → adds 4. Total = 10+9+7+4 = 30. The inner loop starts at i, so it shrinks each outer iteration. Total iterations: 4+3+2+1 = 10, which is n(n-1)/2 — a triangular number. This is O(n^2) complexity. This pattern appears constantly in sorting algorithms like bubble sort and selection sort.
Question 155 · List Sorting and Slicing · hard
A CBSE student writes: 'marks = [85, 92, 78, 95, 88]; marks.sort(); top3 = marks[2:]'. They expect top3 to contain the three highest marks. Evaluate this code — what is the actual output of top3, and how would you fix it to reliably extract the top 3 marks?
Incorrect. After sort(), marks becomes [78, 85, 88, 92, 95] in ascending order. marks[2:] gives [88, 92, 95] — which IS the top 3. But a clearer approach is marks.sort(reverse=True); top3 = marks[:3], which gives [95, 92, 88] in descending order, making the intent explicit
Correct as written. sort() arranges in descending order by default in Python, so marks[2:] skips the two lowest and returns the top 3
Incorrect. marks[2:] causes an IndexError because slicing beyond the midpoint of a sorted list triggers a bounds check in Python 3
Incorrect. sort() returns a new list and does not modify marks in place, so top3 gets [78, 95, 88] — the original unsorted slice from index 2 onward
Answer: A. Incorrect. After sort(), marks becomes [78, 85, 88, 92, 95] in ascending order. marks[2:] gives [88, 92, 95] — which IS the top 3. But a clearer approach is marks.sort(reverse=True); top3 = marks[:3], which gives [95, 92, 88] in descending order, making the intent explicit
Explanationsort() sorts in ascending order by default: [78, 85, 88, 92, 95]. Then marks[2:] slices from index 2 to end: [88, 92, 95]. This does give the top 3 values, so it technically works. However, the intent is fragile — if the list length changes, the magic index 2 breaks. Better: marks.sort(reverse=True); top3 = marks[:3] gives [95, 92, 88], clearly taking the first 3 from a descending sort. Or use sorted(marks, reverse=True)[:3] to avoid mutating the original list.
Question 156 · Linear vs Binary Search · hard
A student implements a simple search: 'def find_item(lst, target): for i in range(len(lst)): if lst[i] == target: return i; return -1'. They call find_item([10, 20, 30, 40, 50], 30). What is returned? Now, if the list had 1 million elements, how many comparisons would this make in the worst case, and what algorithm would reduce this?
Returns 2 (index of 30). Worst case: 1,000,000 comparisons (linear search checks every element). Binary search on a sorted list would reduce worst case to about 20 comparisons (log2 of 1,000,000 ≈ 20), but requires the list to be sorted first
Returns 30 (the value itself). Worst case: 500,000 comparisons because Python optimizes by searching from both ends simultaneously. Hash tables would be faster
Returns 3 (Python uses 1-based indexing internally). Worst case: 100,000 comparisons because modern CPUs process 10 elements per cycle. No better algorithm exists
Returns -1 (not found) because the equality operator == cannot compare integers in a list context. Worst case is irrelevant since the function never finds anything
Answer: A. Returns 2 (index of 30). Worst case: 1,000,000 comparisons (linear search checks every element). Binary search on a sorted list would reduce worst case to about 20 comparisons (log2 of 1,000,000 ≈ 20), but requires the list to be sorted first
ExplanationThe function performs linear search: it checks index 0 (10≠30), index 1 (20≠30), index 2 (30==30) → returns 2. In the worst case (element at end or not present), it checks all n elements: O(n). For n=1,000,000, that is 1,000,000 comparisons. Binary search on a sorted list repeatedly halves the search space: log2(1,000,000) ≈ 20 comparisons. This is the foundational comparison in algorithm design — O(n) vs O(log n) — and explains why sorted data structures and binary search are so important in computer science.
Question 157 · 2D Lists and Column Access · hard
Analyze: 'matrix = [[1,2,3],[4,5,6],[7,8,9]]; col_sum = 0; for row in matrix: col_sum += row[1]'. What value does col_sum hold? Generalize: how would you compute the sum of any column c in an m×n matrix using this pattern?
col_sum = 12. row[1] is treated as accessing the first column of the matrix, giving values 1, 4, and 7, which sum to 12. The general pattern for column c would then be written as: for row in matrix: total += row[c - 1]
col_sum = 15. row[1] accesses index 1 of each row: 2, 5, 8. Sum = 2+5+8 = 15. To generalize for column c: 'col_sum = sum(row[c] for row in matrix)', which uses a generator expression to sum column c across all rows
col_sum = 6. The loop is treated as if row[1] evaluates to a constant value of 2 on every pass rather than reading actual matrix data, so three iterations add 2 each time: 2 + 2 + 2 = 6
col_sum = 45. The loop sums all elements in the matrix because row[1] in Python returns the entire row when used inside a for loop iteration
Answer: B. col_sum = 15. row[1] accesses index 1 of each row: 2, 5, 8. Sum = 2+5+8 = 15. To generalize for column c: 'col_sum = sum(row[c] for row in matrix)', which uses a generator expression to sum column c across all rows
Explanationmatrix is a list of lists (3×3). The for loop iterates over rows: [1,2,3], [4,5,6], [7,8,9]. row[1] accesses index 1 of each row: 2, 5, 8. col_sum = 2+5+8 = 15. The general pattern for column c: sum(row[c] for row in matrix). This is essential for data processing — extracting columns from tabular data stored as nested lists. In NumPy, this becomes matrix[:,c].sum(), but understanding the pure Python approach builds the mental model for how 2D data access works.
Question 158 · List Comprehensions · hard
What is the output of this code: 'result = [x**2 for x in range(1, 6) if x % 2 != 0]; print(result)', and what does tracing each iteration reveal about how list comprehension combines the loop, condition, and transformation into a single expression?
Output: [1, 9, 25]. Trace: x=1 (odd, 1**2=1 ✓), x=2 (even, skip), x=3 (odd, 3**2=9 ✓), x=4 (even, skip), x=5 (odd, 5**2=25 ✓). The comprehension filters odd numbers and squares them in one line, equivalent to a 4-line for loop with if and append
Output: [4, 16]. The condition x % 2 != 0 selects even numbers because != reverses the modulo check, then squares 2 and 4 to get [4, 16]
Output: [1, 4, 9, 16, 25]. The if condition is evaluated after squaring, so all numbers 1-5 are squared first, then filtered — but since all squares are positive, none are removed
Output: [1, 3, 5]. The comprehension returns x values where the condition is true, ignoring the x**2 transformation because the if clause takes precedence over the expression
Answer: A. Output: [1, 9, 25]. Trace: x=1 (odd, 1**2=1 ✓), x=2 (even, skip), x=3 (odd, 3**2=9 ✓), x=4 (even, skip), x=5 (odd, 5**2=25 ✓). The comprehension filters odd numbers and squares them in one line, equivalent to a 4-line for loop with if and append
ExplanationList comprehension syntax: [expression for var in iterable if condition]. Execution order: (1) iterate range(1,6) → x takes values 1,2,3,4,5. (2) Filter: x % 2 != 0 keeps only odd x → 1,3,5. (3) Transform: x**2 squares each → 1,9,25. This produces [1, 9, 25]. The equivalent loop is: result = []; for x in range(1,6): if x%2!=0: result.append(x**2).
Question 159 · Recursion and Base Cases · hard
A student writes a recursive function: 'def factorial(n): return n * factorial(n - 1)'. They call factorial(5) and get a RecursionError. Analyze what happens during execution — what is missing, and how would you fix this function to correctly compute 5! = 120?
Missing: base case. Without 'if n <= 1: return 1', the recursion never stops — factorial(5) calls factorial(4) → factorial(3) → ... → factorial(0) → factorial(-1) → factorial(-2) → forever, until Python hits its default recursion limit of 1000. Fix: add 'if n <= 1: return 1' at the start, which gives 5*4*3*2*1 = 120
The function is correct but Python does not support recursion. All recursive algorithms must be converted to loops because Python's interpreter cannot handle function self-calls
Missing: the multiplication operator * does not work inside recursive calls. Replace n * factorial(n-1) with n + factorial(n-1) to correctly compute the factorial using repeated addition
The error occurs because factorial(n-1) passes an expression, not a variable. Python requires recursive calls to use only simple variable names as arguments, not computed values
Answer: A. Missing: base case. Without 'if n <= 1: return 1', the recursion never stops — factorial(5) calls factorial(4) → factorial(3) → ... → factorial(0) → factorial(-1) → factorial(-2) → forever, until Python hits its default recursion limit of 1000. Fix: add 'if n <= 1: return 1' at the start, which gives 5*4*3*2*1 = 120
ExplanationEvery recursive function needs a base case — a condition where it returns without calling itself. Without it, recursion is infinite. Call trace: factorial(5) → 5 * factorial(4) → 4 * factorial(3) → 3 * factorial(2) → 2 * factorial(1) → 1 * factorial(0) → 0 * factorial(-1) → ... Python's default recursion limit is 1000, so after 1000 frames, it raises RecursionError. Fix: 'def factorial(n): if n <= 1: return 1; return n * factorial(n-1)'. Now: factorial(5) = 5*4*3*2*1 = 120, with exactly 5 recursive calls. Base cases prevent infinite recursion in all recursive algorithms: binary search, tree traversal, merge sort.
Question 160 · Web Development Basics: Build Your First Website · hard
Rohan is building his very first website for a school project. He wants a highlighted box announcing "Sports Day – 15th August" on the homepage, so he writes this CSS for the box (no box-sizing property is set anywhere in his stylesheet, so the browser uses its default behaviour):
```css
.notice {
width: 240px;
padding: 15px;
border: 3px solid #333;
margin: 10px;
}
```
When this box renders in the browser, what is its total width in pixels, measured from the left edge of the border to the right edge of the border (excluding the margin)?
276 pixels, since the declared width sets only the content area and both the padding and border add to each side of the box separately.
240 pixels, since padding and border are drawn inside the declared width and do not add anything to the box's total size.
258 pixels, since only one side's padding and one side's border need to be added to the declared width.
296 pixels, since padding, border, and margin are all added directly to the declared width to get the box's total size on the page.
Answer: A. 276 pixels, since the declared width sets only the content area and both the padding and border add to each side of the box separately.
ExplanationBy default (content-box, the standard box-sizing model unless overridden), the width property sets only the size of the content area — padding and border are added on top of it, separately on the left side and the right side. Here the content area is 240px wide. Padding adds 15px on the left and 15px on the right, contributing 30px in total, and the border adds 3px on the left and 3px on the right, contributing 6px in total. Adding these together gives 240 + 30 + 6 = 276px as the box's rendered width, measured to the outer edge of the border.
Margin sits outside the border and only pushes neighbouring elements away — it never adds to the element's own width, so folding it into the box's size (296px) is incorrect. Assuming the declared width already equals the final rendered size (240px) mistakes content-box for border-box behaviour, which only applies when a developer explicitly writes box-sizing: border-box — it is never the default. And adding padding and border for just one side instead of doubling them (258px) misses that padding and border apply independently to both the left and right edges of a block-level box, not once overall.