MauryaHub PYQ Practice

Programming in Python · End Term · Sep 2025 · AN

Programming in Python · End Term · Sep 2025 AN

← Course papers · Start practice / exam

Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.

18 / 18 published solutions

Question 2 MCQ · 3.0 marks

Consider the following functions: def f(n): if n < 10: return n return f(n // 10) def g(n): if n < 10: return 1 return 1 + g(n // 10) def h(n): if n == 0: return 1 return n * h(n - 1) Which of the following function calls returns the unit digit of (10!) ?
6406536029472.
g(h(10))
6406536029473.
f(h(10))
6406536029474.
h(f(10))
6406536029475.
f(g(10))

Published solution

**1. Analyze the three recursive functions:** - **`h(n)`:** - Base case: `if n == 0: return 1` - Recursive step: `return n * h(n - 1)` - This computes the factorial $n!$. Thus, `h(10)` returns $10! = 3628800$. - **`g(n)`:** - Base case: `if n < 10: return 1` - Recursive step: `return 1 + g(n // 10)` - This counts the total number of digits in the positive integer $n$. - **`f(n)`:** - Extracts a single digit from `n` by repeatedly dividing by $10$ (`n // 10`) until a single-digit number (`n < 10`) is reached. **2. Evaluate the composite function call:** To first compute $10!$ and then extract its digit using `f`, we must pass `h(10)` as the argument to `f`, giving **`f(h(10))`**. **Answer: Option B** A: **Incorrect:** `g(h(10))` counts the number of digits in $10!$ using `g`, rather than extracting a digit with `f`. B: **Correct:** `h(10)` computes $10!$, and passing that result into `f` as `f(h(10))` extracts the single digit. C: **Incorrect:** `h(f(10))` first evaluates `f(10) = 1` and then computes $1! = 1$, instead of operating on $10!$. D: **Incorrect:** `f(g(10))` counts the digits of $10$ (`g(10) = 2`) and passes $2$ to `f`, never computing $10!$.

Report a correction for Q2

Question 3 MCQ · 3.0 marks

Consider the following Python code that writes product information to a CSV file named "products.csv": def write_products(items): f = open('products.csv', 'w') f.write('Product,Price,Stock\n') for i in range(len(items)): name, price, stock = items[i] line = f'{name},{price},{stock}' if i != len(items) - 1: line = line + '\n' f.write(line) f.close() data = [('Keyboard', 1200, 50), ('Mouse', 800, 75), ('Monitor', 9500, 20), ('CPU', 32000, 10)] write_products(data) If the above code is executed successfully, what will be the exact contents of the file "products.csv"?
6406536029476.
Keyboard,1200,50 Mouse,800,75 Monitor,9500,20 CPU,32000,10
6406536029477.
Product,Price,Stock Keyboard,1200,50 Mouse,800,75 Monitor,9500,20 CPU,32000,10
6406536029478.
Product,Price Stock Keyboard,1200,50 Mouse,800,75 Monitor,9500,20 CPU,32000,10
6406536029479.
Price,Stock,Product Keyboard,1200,50 Mouse,800,75 Monitor,9500,20 CPU,32000,10

Published solution

**1. Trace the file writing operations in `write_products(items)`:** 1. `f = open('products.csv', 'w')` opens `products.csv` for writing. 2. `f.write('Product,Price,Stock\n')` writes the header row `'Product,Price,Stock'` followed by a newline. 3. The `for` loop iterates over `i` from `0` to `3` (`len(items) = 4`): - `i = 0`: writes `'Keyboard,1200,50\n'` - `i = 1`: writes `'Mouse,800,75\n'` - `i = 2`: writes `'Monitor,9500,20\n'` - `i = 3` (`i == len(items) - 1`): writes `'CPU,32000,10'` without a trailing newline. **2. Conclude:** The file begins with the header line `Product,Price,Stock` followed by the four comma-separated product lines in order. **Answer: Option B** A: **Incorrect:** This omits the header line `'Product,Price,Stock\n'` written before the loop. B: **Correct:** The file contains the header `'Product,Price,Stock'` on the first line followed by the four product records. C: **Incorrect:** The header string `'Product,Price,Stock\n'` has commas between all three column names, not a newline before `'Stock'`. D: **Incorrect:** The header columns are written as `'Product,Price,Stock'`, not `'Price,Stock,Product'`.

Report a correction for Q3

Question 4 MCQ · 3.0 marks

What will be the output of the following Python code? word1 = 'program' word2 = 'algorithm' L = [] for i in range(len(word1)): for j in range(len(word2)): if word1[i] != word2[j]: L.append(word1[i]) break else: continue print(L)
6406536029480.
['p', 'r', 'o', 'g', 'r', 'a', 'm']
6406536029481.
['r', 'o', 'g', 'r', 'a', 'm']
6406536029482.
['r', 'o', 'g', 'a', 'm']
6406536029483.
['a', 'l', 'g', 'o', 'r', 'i', 't', 'h', 'm']

Published solution

**1. Trace the nested loops:** - `word1 = 'program'` and `word2 = 'algorithm'`. - For each index `i` in `range(len(word1))`, the inner loop checks `j` in `range(len(word2))`: ```python if word1[i] != word2[j]: L.append(word1[i]) break ``` - Notice the condition: as soon as `word1[i]` is **not equal** to `word2[j]`, `word1[i]` is appended to `L` and the inner loop immediately terminates via `break`! **2. Check each character of `word1` (`'program'`):** - For `'p'`, `'r'`, `'o'`, `'g'`, `'r'`, `'m'`: none of these equals `word2[0]` (`'a'`), so on the very first check (`j = 0`), `word1[i] != 'a'` is `True`, the character is appended to `L`, and `break` executes. - For `'a'` (`i = 5`): at `j = 0`, `'a' == word2[0]` (`'a'`), so the `else: continue` branch runs and moves to `j = 1`. At `j = 1`, `word2[1]` is `'l'`, and since `'a' != 'l'`, `'a'` is appended to `L` and `break` executes. **3. Conclude:** Every character of `'program'` is appended to `L` in order, producing `['p', 'r', 'o', 'g', 'r', 'a', 'm']`. **Answer: Option A** A: **Correct:** Because every character in `'program'` differs from at least one character in `'algorithm'`, the `if` condition triggers and breaks once for each character of `word1`. B: **Incorrect:** `'p'` at index 0 is not equal to `'a'`, so `'p'` is also appended to `L`. C: **Incorrect:** Both `'p'` and the second `'r'` are appended because each index `i` of `word1` is processed independently. D: **Incorrect:** The code appends `word1[i]` (characters from `'program'`), not characters from `word2` (`'algorithm'`).

Report a correction for Q4

Question 5 MCQ · 3.0 marks

What is the output of the following snippet of code? s = 'machinelearningwithpython' D = {} for ch in s: D[ch] = D.get(ch, 0) + 1 mch = '' mcv = -1 for k in sorted(D.keys()): if D[k] > mcv: mcv = D[k] mch = k print(mch)
6406536029484.
i
6406536029485.
n
6406536029486.
e
6406536029487.
a

Published solution

**1. Understand what the code computes:** - The first `for` loop builds a frequency dictionary `D` mapping each character `ch` in `s = 'machinelearningwithpython'` to how many times it appears in `s`. - The second `for` loop iterates over the keys in alphabetical order (`sorted(D.keys())`) and finds the character `mch` with the highest frequency `mcv`. **2. Count the frequencies of the candidate characters in `'machinelearningwithpython'`:** - `'a'`: appears $2$ times (`m-a-chinele-a-rning...`) - `'e'`: appears $2$ times (`machin-e-l-e-arning...`) - `'i'`: appears $3$ times (`mach-i-nelearn-i-ngw-i-thpython`) - `'h'`: appears $3$ times (`mac-h-inelearningwit-h-pyt-h-on`) - `'n'`: appears $4$ times (`machi-n-elear-n-i-n-gwithpytho-n`) **3. Conclude:** Since `'n'` has the maximum count of $4$, `mch` is `'n'`. **Answer: Option B** A: **Incorrect:** `'i'` appears 3 times in the string, which is less than the 4 occurrences of `'n'`. B: **Correct:** `'n'` occurs 4 times in `'machinelearningwithpython'`, which is the highest frequency of any character. C: **Incorrect:** `'e'` appears only 2 times in the string. D: **Incorrect:** `'a'` appears only 2 times in the string.

Report a correction for Q5

Question 6 MCQ · 3.0 marks

If n is a positive integer, what does the following snippet compute as the output? Q = [x for x in range(1, n + 1) if x % 3 == 1] print(sum(Q))
6406536029488.
1+2+3+…+n
6406536029489.
3+6+9+…+3n
6406536029490.
1+4+7+…+(3n+1)
6406536029491.
1+4+7+…+(3k+1≤n)

Published solution

**1. Analyze the list comprehension:** ```python Q = [x for x in range(1, n + 1) if x % 3 == 1] print(sum(Q)) ``` - `range(1, n + 1)` generates all integers $x$ from $1$ up to $n$ inclusive ($1 \le x \le n$). - The filter `x % 3 == 1` selects numbers that leave a remainder of $1$ when divided by $3$, which are numbers of the form $3k + 1$ for $k = 0, 1, 2, \dots$, namely $1, 4, 7, 10, \dots$, provided $3k + 1 \le n$. **2. Conclude:** `sum(Q)` adds all numbers of the form $3k + 1$ that do not exceed $n$: $$1 + 4 + 7 + \dots + (3k + 1 \le n)$$ **Answer: Option D** A: **Incorrect:** The condition `if x % 3 == 1` filters out numbers whose remainder modulo 3 is 0 or 2. B: **Incorrect:** Multiples of 3 satisfy `x % 3 == 0`, not `x % 3 == 1`. C: **Incorrect:** The upper bound of `range(1, n + 1)` is $n$, so the last term cannot exceed $n$ (it does not go up to $3n + 1$). D: **Correct:** It sums all positive integers $x \le n$ of the form $3k + 1$, i.e., $1 + 4 + 7 + \dots + (3k + 1 \le n)$.

Report a correction for Q6

Question 7 MCQ · 3.0 marks

Consider the following snippets of code: **Code-1** T = ([],) T[0].append(10) **Code-2** U = (1, 2, 3) U[0] = 5 **Code-3** V = ([1, 2], [3, 4]) V[0] = (5, 6) Select the most appropriate statement.
6406536029492.
Code-1 and Code-2 will throw an error in line-2
6406536029493.
Only code-2 will throw an error in line-2
6406536029494.
Only code-3 will throw an error in line-2
6406536029495.
Code-2 and Code-3 will throw an error

Published solution

**1. Analyze each code snippet:** - **Code-1:** ```python T = ([],) T[0].append(10) ``` `T` is a 1-element tuple whose element `T[0]` is a mutable list `[]`. Calling `T[0].append(10)` mutates the list inside the tuple without changing which object `T[0]` references. Thus, **Code-1 runs without any error** (and `T` becomes `([10],)`). - **Code-2:** ```python U = (1, 2, 3) U[0] = 5 ``` `U` is a tuple, and tuples are immutable in Python. Reassigning `U[0] = 5` raises a `TypeError: 'tuple' object does not support item assignment`. - **Code-3:** ```python V = ([1, 2], [3, 4]) V[0] = (5, 6) ``` `V` is also a tuple. Even though its elements are lists, attempting to reassign the tuple slot `V[0] = (5, 6)` directly modifies the tuple structure and raises a `TypeError: 'tuple' object does not support item assignment`. **2. Conclude:** Both **Code-2 and Code-3 will throw an error**. **Answer: Option D** A: **Incorrect:** Code-1 does not throw an error because it mutates the inner list `T[0]` in place rather than reassigning the tuple index. B: **Incorrect:** Code-3 also throws a `TypeError` because `V` is a tuple and `V[0] = (5, 6)` attempts tuple item assignment. C: **Incorrect:** Code-2 also throws a `TypeError` because `U` is an immutable tuple. D: **Correct:** Both Code-2 and Code-3 attempt item assignment (`U[0] = ...` and `V[0] = ...`) on a tuple, which raises a `TypeError`.

Report a correction for Q7

Question 8 MSQ · 3.0 marks

students is a list of tuples. Each tuple is of the form (name, marks) . Select all snippets of code that create a list toppers containing the names of students who scored at least 85 marks. You can assume that students is already defined. **Sample Input** students = [('Amit', 92), ('Bina', 78), ('Chetan', 88), ('Deepa', 84), ('Esha', 91)] **Sample Output** ['Amit', 'Esha', 'Chetan']
6406536029496.
toppers = sorted( [name for name, m in students if m >= 85] )
6406536029497.
toppers = [ x[0] for x in sorted(students, key=lambda s: s[1], reverse=True) if x[1] >= 85 ]
6406536029498.
toppers = [s for s in students if s[1] >= 85].sort()
6406536029499.
toppers = list( map( lambda x: x[0], filter( lambda x: x[1] >= 85, sorted(students, key=lambda s: s[1], reverse=True) ) ) )

Published solution

**1. Check the required output from the sample:** - Sample Input: `students = [('Amit', 92), ('Bina', 78), ('Chetan', 88), ('Deepa', 84), ('Esha', 91)]` - Sample Output: `['Amit', 'Esha', 'Chetan']` - Notice that the students with marks $\ge 85$ are Amit ($92$), Esha ($91$), and Chetan ($88$), sorted in **descending order of their marks**. **2. Evaluate each option:** - **Option A:** `sorted([name for name, m in students if m >= 85])` sorts the names alphabetically (`['Amit', 'Chetan', 'Esha']`), which does not match the sample output `['Amit', 'Esha', 'Chetan']`. - **Option B:** Sorts `students` by marks `s[1]` in descending order (`reverse=True`), filters those with `x[1] >= 85`, and extracts their names `x[0]`. This produces `['Amit', 'Esha', 'Chetan']`. (**Correct**) - **Option C:** `.sort()` sorts a list in place and returns `None`, so `toppers` becomes `None`. - **Option D:** Sorts `students` by marks descending, uses `filter` to keep tuples with `x[1] >= 85`, and uses `map` to extract the name `x[0]`, converting the result to a list `['Amit', 'Esha', 'Chetan']`. (**Correct**) **Answer: Options B, D** A: **Incorrect:** Sorting a list of strings sorts them alphabetically (`['Amit', 'Chetan', 'Esha']`) rather than by descending marks. B: **Correct:** Sorts the student tuples by marks in descending order, filters for marks $\ge 85$, and extracts the student names. C: **Incorrect:** `list.sort()` modifies the list in place and returns `None`, and it would also sort tuples rather than extracting names. D: **Correct:** Uses `sorted`, `filter`, and `map` to sort by marks descending, keep scores $\ge 85$, and extract the names into a list.

Report a correction for Q8

Question 9 MCQ · 3.0 marks

Consider the following snippet: f = open('records.csv', 'r') D = dict() for line in f: name, subject, test_type, marks = line.strip().split(',') marks = int(marks) if name not in D: D[name] = dict() if subject not in D[name]: D[name][subject] = dict() D[name][subject][test_type] = marks print(D) This code produces the given output: { 'Amit': { 'Math': {'Mid': 40, 'Final': 85}, 'Physics': {'Mid': 42} }, 'Bina': { 'Math': {'Final': 90}, 'Chemistry': {'Mid': 44, 'Final': 88} } } Which of the following files **records.csv** could have generated the above dictionary?
6406536029500.
Amit,Math,Mid,40 Amit,Math,Final,85 Amit,Physics,Mid,42 Bina,Math,Final,90 Bina,Chemistry,Mid,44 Bina,Chemistry,Final,88
6406536029501.
Bina,Chemistry,Mid,44 Amit,Math,Mid,40 Bina,Math,Final,90 Amit,Physics,Mid,42 Amit,Math,Final,85 Bina,Chemistry,Final,88
6406536029502.
Amit,Physics,Mid,42 Amit,Math,Mid,40 Amit,Math,Final,85 Bina,Chemistry,Final,88 Bina,Math,Final,90 Bina,Chemistry,Mid,44
6406536029503.
Amit,Math,Final,85 Amit,Math,Mid,40 Amit,Physics,Mid,42 Bina,Math,Final,90 Bina,Chemistry,Final,88 Bina,Chemistry,Mid,44

Published solution

**1. Understand dictionary insertion order in Python:** In Python (3.7+), dictionaries preserve the **exact order in which keys are first inserted**. **2. Check the key order in the printed output dictionary `D`:** ```python { 'Amit': { 'Math': {'Mid': 40, 'Final': 85}, 'Physics': {'Mid': 42} }, 'Bina': { 'Math': {'Final': 90}, 'Chemistry': {'Mid': 44, 'Final': 88} } } ``` From this output order: 1. `'Amit'` must appear before `'Bina'` in the CSV file. 2. For `'Amit'`, `'Math'` must appear before `'Physics'`, and within `'Math'`, `'Mid'` ($40$) must appear before `'Final'` ($85$). 3. For `'Bina'`, `'Math'` must appear before `'Chemistry'`, and within `'Chemistry'`, `'Mid'` ($44$) must appear before `'Final'` ($88$). **3. Match with the options:** Only **Option A** lists the records in an order that satisfies all of these first-insertion order constraints. **Answer: Option A** A: **Correct:** Inserts `'Amit'` before `'Bina'`, `'Math'` before `'Physics'`, `'Mid'` before `'Final'` for Amit's Math, and `'Math'` before `'Chemistry'` (with `'Mid'` before `'Final'`) for Bina. B: **Incorrect:** Starts with `'Bina'`, which would make `'Bina'` the first key in `D` instead of `'Amit'`. C: **Incorrect:** Lists `'Amit,Physics,Mid,42'` first, which would put `'Physics'` before `'Math'` in `D['Amit']`. D: **Incorrect:** Lists `'Amit,Math,Final,85'` before `'Amit,Math,Mid,40'`, which would put `'Final'` before `'Mid'` in `D['Amit']['Math']`.

Report a correction for Q9

Question 10 MSQ · 3.0 marks

Consider the following snippet of code: def analyze_string(s, k): flag = 0 counts = dict() for ch in s: if ch not in counts: counts[ch] = 0 counts[ch] += 1 for ch in counts: if counts[ch] > k: flag = 1 break if flag == 0: print("Within Limit") else: print("Too Frequent") if input_str.isalpha(): print("Alpha") else: print("Non-Alpha") analyze_string(input_str, 1) input_str is a string variable that has already been defined. The above code runs without any errors. The output when the code given above is executed is as follows: Alpha Too Frequent Which of the following statements are True? Note that your answer should hold for any value of the string input_str that results in the above output.
6406536029504.
input_str contains only alphabetic characters.
6406536029505.
input_str contains at least one non-alphabetic character.
6406536029506.
Every character in input_str occurs exactly once.
6406536029507.
At least one character in input_str occurs more than once.

Published solution

**1. Analyze the first line of output (`Alpha`):** The code checks: ```python if input_str.isalpha(): print("Alpha") else: print("Non-Alpha") ``` Since `"Alpha"` is printed, `input_str.isalpha()` evaluated to `True`, which means **`input_str` contains only alphabetic characters** (Statement A is true, Statement B is false). **2. Analyze the second line of output (`Too Frequent`):** Next, `analyze_string(input_str, 1)` counts the frequency of each character in `input_str` and checks: ```python if counts[ch] > k: # here k = 1 flag = 1 break ``` Since `"Too Frequent"` is printed, `flag` must be `1`, meaning `counts[ch] > 1` for at least one character `ch`. Therefore, **at least one character in `input_str` occurs more than once** (Statement D is true, Statement C is false). **Answer: Options A, D** A: **Correct:** Because `input_str.isalpha()` returned `True` (printing `'Alpha'`), every character in `input_str` is alphabetic. B: **Incorrect:** If `input_str` contained any non-alphabetic character, `input_str.isalpha()` would be `False` and `'Non-Alpha'` would be printed. C: **Incorrect:** If every character occurred at most once, `flag` would remain `0` and `'Within Limit'` would be printed. D: **Correct:** Printing `'Too Frequent'` when `k = 1` means `counts[ch] > 1` for at least one character.

Report a correction for Q10

Question 11 NAT · 3.0 marks

What is the output of the following snippet of code? def split_sum(L): if len(L) == 0: return 0 if len(L) == 1: return L[0] mid = len(L) // 2 left = split_sum(L[:mid]) right = split_sum(L[mid+1:]) return left - right nums = [1, 2, 3, 4, 5] print(split_sum(nums))

Published solution

**1. Understand the recursive function `split_sum(L)`:** - Base cases: - If `len(L) == 0`, return `0`. - If `len(L) == 1`, return `L[0]`. - Recursive step for `len(L) >= 2`: - `mid = len(L) // 2` - `left = split_sum(L[:mid])` (elements before index `mid`) - `right = split_sum(L[mid+1:])` (elements after index `mid`; note that `L[mid]` is skipped) - Returns `left - right`. **2. Trace `split_sum([1, 2, 3, 4, 5])`:** - For `L = [1, 2, 3, 4, 5]`, `len(L) = 5`, so `mid = 5 // 2 = 2`. - `L[:2]` is `[1, 2]` - `L[3:]` is `[4, 5]` - Compute `left = split_sum([1, 2])`: - `len([1, 2]) = 2`, so `mid = 2 // 2 = 1`. - `left_1 = split_sum([1]) = 1` - `right_1 = split_sum([]) = 0` - `split_sum([1, 2]) = 1 - 0 = 1`. - Compute `right = split_sum([4, 5])`: - `len([4, 5]) = 2`, so `mid = 2 // 2 = 1`. - `left_2 = split_sum([4]) = 4` - `right_2 = split_sum([]) = 0` - `split_sum([4, 5]) = 4 - 0 = 4`. - Combine at the top level: $$\text{left} - \text{right} = 1 - 4 = -3$$ **Answer: -3**

Report a correction for Q11

Question 12 NAT · 3.0 marks

What is the output of the following snippet of code if it is given that the except block is executed at least once? total = 1 errors = 0 for x in [10, '5', 0, 'abc', 2]: try: n = 10 // int(x) total *= n except ZeroDivisionError: errors += 2 total += 5 except ValueError: errors += 1 total -= 3 print(total + errors)

Published solution

**1. Initialize variables:** - `total = 1` - `errors = 0` **2. Trace the loop over `x in [10, '5', 0, 'abc', 2]`:** 1. **`x = 10`:** - `int(10)` is `10`, `n = 10 // 10 = 1`. - `total *= 1` $\implies$ `total = 1`, `errors = 0`. 2. **`x = '5'`:** - `int('5')` is `5`, `n = 10 // 5 = 2`. - `total *= 2` $\implies$ `total = 2`, `errors = 0`. 3. **`x = 0`:** - `int(0)` is `0`, `10 // 0` raises `ZeroDivisionError`. - In `except ZeroDivisionError:`: - `errors += 2` $\implies$ `errors = 2` - `total += 5` $\implies$ `total = 2 + 5 = 7`. 4. **`x = 'abc'`:** - `int('abc')` raises `ValueError`. - In `except ValueError:`: - `errors += 1` $\implies$ `errors = 2 + 1 = 3` - `total -= 3` $\implies$ `total = 7 - 3 = 4`. 5. **`x = 2`:** - `int(2)` is `2`, `n = 10 // 2 = 5`. - `total *= 5` $\implies$ `total = 4 * 5 = 20`, `errors = 3`. **3. Compute the final output:** $$\text{total} + \text{errors} = 20 + 3 = 23$$ **Answer: 23**

Report a correction for Q12

Question 13 NAT · 3.0 marks

What is the output of the following snippet of code? def is_prime(x): if x < 2: return False for i in range(2, int(x**0.5) + 1): if x % i == 0: return False return True total = 0 for num in range(10, 21): if is_prime(num) and is_prime(sum(int(d) for d in str(num))): total += num print(total)

Published solution

**1. Understand the condition in the loop:** The loop checks integers `num` in `range(10, 21)` (i.e., $10, 11, 12, \dots, 20$). An integer `num` is added to `total` if: 1. `is_prime(num)` is `True` (`num` is a prime number), **and** 2. `is_prime(sum(int(d) for d in str(num)))` is `True` (the sum of the digits of `num` is also a prime number). **2. Test the prime numbers between $10$ and $20$:** - **`num = 11`:** Prime. Sum of digits $= 1 + 1 = 2$, and $2$ is prime (`is_prime(2)` is `True`). So $11$ is added to `total`. - **`num = 13`:** Prime. Sum of digits $= 1 + 3 = 4$, which is not prime. - **`num = 17`:** Prime. Sum of digits $= 1 + 7 = 8$, which is not prime. - **`num = 19`:** Prime. Sum of digits $= 1 + 9 = 10$, which is not prime. **3. Conclude:** Only `11` satisfies both conditions, so `total = 11`. **Answer: 11**

Report a correction for Q13

Question 14 NAT · 3.0 marks

Consider the following snippet of code: L = [1, 2, 3] S = [] T = 0 i = 0 while i < len(L): S += L[i:] for j in S: T += j i += 1 print(T) What is the output when the above code is executed?

Published solution

**1. Initialize variables:** - `L = [1, 2, 3]` (`len(L) = 3`) - `S = []`, `T = 0`, `i = 0` **2. Trace each iteration of the `while i < 3` loop:** - **Iteration 1 (`i = 0`):** - `L[0:]` is `[1, 2, 3]`. - `S += [1, 2, 3]` $\implies$ `S = [1, 2, 3]`. - The inner loop adds all elements of `S` to `T`: $$T = 0 + (1 + 2 + 3) = 6$$ - `i` becomes `1`. - **Iteration 2 (`i = 1`):** - `L[1:]` is `[2, 3]`. - `S += [2, 3]` $\implies$ `S = [1, 2, 3, 2, 3]`. - The inner loop adds all elements of `S` (sum $= 1 + 2 + 3 + 2 + 3 = 11$) to `T`: $$T = 6 + 11 = 17$$ - `i` becomes `2`. - **Iteration 3 (`i = 2`):** - `L[2:]` is `[3]`. - `S += [3]` $\implies$ `S = [1, 2, 3, 2, 3, 3]`. - The inner loop adds all elements of `S` (sum $= 11 + 3 = 14$) to `T`: $$T = 17 + 14 = 31$$ - `i` becomes `3`, and the loop terminates. **3. Conclude:** `print(T)` outputs `31`. **Answer: 31**

Report a correction for Q14

Question 15 NAT · 3.0 marks

What is the output of the following snippet of code? def digit_rec(n): if n < 10: return n s = sum(int(d) for d in str(n)) return digit_rec(s) + (n % 10) a = digit_rec(987) b = digit_rec(1234) print(a - b)

Published solution

**1. Understand the recursive function `digit_rec(n)`:** - If `n < 10`, it returns `n`. - Otherwise, it computes the sum of digits `s` of `n`, and returns `digit_rec(s) + (n % 10)` (where `n % 10` is the last digit of `n`). **2. Evaluate `a = digit_rec(987)`:** - For `n = 987`: digit sum `s = 9 + 8 + 7 = 24`, last digit `987 % 10 = 7`. $$\text{digit\_rec}(987) = \text{digit\_rec}(24) + 7$$ - For `n = 24`: digit sum `s = 2 + 4 = 6`, last digit `24 % 10 = 4`. $$\text{digit\_rec}(24) = \text{digit\_rec}(6) + 4 = 6 + 4 = 10$$ - Therefore: $$a = 10 + 7 = 17$$ **3. Evaluate `b = digit_rec(1234)`:** - For `n = 1234`: digit sum `s = 1 + 2 + 3 + 4 = 10`, last digit `1234 % 10 = 4`. $$\text{digit\_rec}(1234) = \text{digit\_rec}(10) + 4$$ - For `n = 10`: digit sum `s = 1 + 0 = 1`, last digit `10 % 10 = 0`. $$\text{digit\_rec}(10) = \text{digit\_rec}(1) + 0 = 1 + 0 = 1$$ - Therefore: $$b = 1 + 4 = 5$$ **4. Compute `a - b`:** $$a - b = 17 - 5 = 12$$ **Answer: 12**

Report a correction for Q15

Question 16 MCQ · 2.0 marks

You are inside the lift of a building. There are 8 levels in the building: [−3,−2,−1,0,1,2,3,4] The number 0 is the ground floor. Positive numbers correspond to floors above the ground floor, negative numbers correspond to basement levels below the ground floor. The lift has only two buttons. The button U will take you one level up and the button D will take you one level down. You make a sequence of presses. # presses contains the sequence of button presses made by you presses = 'UUDDUDUUUD' floor = 0 count_up = 0 count_down = 0 for i in range(len(presses)): char = presses[i] if char == 'U': floor += 1 count_up += 1 else: floor -= 1 count_down += 1 if floor == 3: print("Reached 3rd floor at:", i + 1) break print("Ups:", count_up) print("Downs:", count_down) Based on the above data solve the subsequent questions.
What is printed by the statement inside the loop (print("Reached 3rd floor at:", i + 1)) ?
6406536029513.
Reached 3rd floor at: 6
6406536029514.
Reached 3rd floor at: 7
6406536029515.
Reached 3rd floor at: 8
6406536029516.
Reached 3rd floor at: 9

Published solution

**1. Trace the lift movement for `presses = 'UUDDUDUUUD'` starting at `floor = 0`:**
Index `i``i + 1`Button `char``floor` after press`count_up``count_down`
01`'U'`$1$$1$$0$
12`'U'`$2$$2$$0$
23`'D'`$1$$2$$1$
34`'D'`$0$$2$$2$
45`'U'`$1$$3$$2$
56`'D'`$0$$3$$3$
67`'U'`$1$$4$$3$
78`'U'`$2$$5$$3$
89`'U'`$3$$6$$3$
**2. Check when `floor == 3` is reached:** At index `i = 8` (the 9th press), `floor` becomes `3`. The condition `if floor == 3:` is satisfied, printing: `Reached 3rd floor at: 9` (since `i + 1 = 8 + 1 = 9`), and then `break` exits the loop. **Answer: Option D** A: **Incorrect:** After 6 presses (`i = 5`), the lift is at floor 0, not floor 3. B: **Incorrect:** After 7 presses (`i = 6`), the lift is at floor 1. C: **Incorrect:** After 8 presses (`i = 7`), the lift is at floor 2. D: **Correct:** On the 9th button press (`i = 8`), `floor` reaches 3 and `i + 1 = 9` is printed.

Report a correction for Q16

Question 17 MCQ · 2.0 marks

You are inside the lift of a building. There are 8 levels in the building: [−3,−2,−1,0,1,2,3,4] The number 0 is the ground floor. Positive numbers correspond to floors above the ground floor, negative numbers correspond to basement levels below the ground floor. The lift has only two buttons. The button U will take you one level up and the button D will take you one level down. You make a sequence of presses. # presses contains the sequence of button presses made by you presses = 'UUDDUDUUUD' floor = 0 count_up = 0 count_down = 0 for i in range(len(presses)): char = presses[i] if char == 'U': floor += 1 count_up += 1 else: floor -= 1 count_down += 1 if floor == 3: print("Reached 3rd floor at:", i + 1) break print("Ups:", count_up) print("Downs:", count_down) Based on the above data solve the subsequent questions.
What are the values printed for "Ups:" and "Downs:" after program execution?
6406536029517.
Ups: 5, Downs: 5
6406536029518.
Ups: 6, Downs: 3
6406536029519.
Ups: 7, Downs: 3
6406536029520.
Ups: 8, Downs: 2

Published solution

**1. Count the `'U'` and `'D'` presses up to the `break` statement:** From the trace of `presses = 'UUDDUDUUUD'`: - The loop stops via `break` at index `i = 8` (the 9th character, before the final `'D'` at index 9 is ever processed). - In the first 9 characters `'UUDDUDUUU'`: - Number of `'U'` presses: `count_up = 6` - Number of `'D'` presses: `count_down = 3` **2. Conclude:** The program prints `Ups: 6` and `Downs: 3`. **Answer: Option B** A: **Incorrect:** There are only 4 `'D'` characters in the entire string, and the loop breaks before the 10th character. B: **Correct:** Up to index `i = 8` when `floor == 3` triggers `break`, 6 `'U'` presses and 3 `'D'` presses have been executed. C: **Incorrect:** `count_up` is 6, not 7. D: **Incorrect:** `count_up` is 6 and `count_down` is 3.

Report a correction for Q17

Question 18 MSQ · 2.0 marks

Consider the following python code to answer the subsequent questions. def move_elems(M): n = len(M) temp = M[0][0] for j in range(n - 1): M[0][j] = M[0][j + 1] for i in range(n - 1): M[i][n - 1] = M[i + 1][n - 1] M[n-1][n-1] = temp return M def mat_sum(M): total = 0 n = len(M) for i in range(n): total += M[i][n - i - 1] return total M = [[3, 5, 7], [9, 11, 13], [15, 17, 19]] R = move_elems(M) print(R) print(mat_sum(R))
What is the first line of output?
6406536029521.
[[5, 7, 13], [3, 11, 19], [9, 15, 17]]
6406536029522.
[[5, 7, 13], [9, 11, 19], [15, 17, 3]]
6406536029523.
[[5, 7, 13], [3, 11, 19], [15, 9, 17]]
6406536029524.
[[5, 7, 9], [3, 11, 13], [15, 17, 19]]

Published solution

**1. Trace `move_elems(M)` on the $3 \times 3$ matrix `M`:** Initial matrix (`n = 3`): $$M = \begin{bmatrix} 3 & 5 & 7 \\ 9 & 11 & 13 \\ 15 & 17 & 19 \end{bmatrix}$$ 1. `temp = M[0][0]` saves `temp = 3`. 2. First loop (`for j in range(2): M[0][j] = M[0][j + 1]`): - `j = 0`: `M[0][0] = M[0][1] = 5` - `j = 1`: `M[0][1] = M[0][2] = 7` - Row 0 is now `[5, 7, 7]`. 3. Second loop (`for i in range(2): M[i][2] = M[i + 1][2]`): - `i = 0`: `M[0][2] = M[1][2] = 13` (Row 0 becomes `[5, 7, 13]`) - `i = 1`: `M[1][2] = M[2][2] = 19` (Row 1 becomes `[9, 11, 19]`) 4. `M[2][2] = temp` sets `M[2][2] = 3` (Row 2 becomes `[15, 17, 3]`). **2. Conclude:** The returned matrix `R` printed on the first line is `[[5, 7, 13], [9, 11, 19], [15, 17, 3]]`. **Answer: Option B** A: **Incorrect:** The first column and bottom row are not shifted by `move_elems`; only the first row and last column are shifted. B: **Correct:** Shifting the top row left, the last column up, and placing `temp = 3` at `M[2][2]` gives `[[5, 7, 13], [9, 11, 19], [15, 17, 3]]`. C: **Incorrect:** `M[1][0]` remains `9` and `M[2][2]` becomes `3`. D: **Incorrect:** The last column elements are shifted up and `M[2][2]` is overwritten with `3`.

Report a correction for Q18

Question 19 NAT · 2.0 marks

Consider the following python code to answer the subsequent questions. def move_elems(M): n = len(M) temp = M[0][0] for j in range(n - 1): M[0][j] = M[0][j + 1] for i in range(n - 1): M[i][n - 1] = M[i + 1][n - 1] M[n-1][n-1] = temp return M def mat_sum(M): total = 0 n = len(M) for i in range(n): total += M[i][n - i - 1] return total M = [[3, 5, 7], [9, 11, 13], [15, 17, 19]] R = move_elems(M) print(R) print(mat_sum(R))
What is the second line of output?

Published solution

**1. Understand what `mat_sum(R)` computes:** ```python for i in range(n): total += M[i][n - i - 1] ``` For `n = 3`, this sums the elements along the **secondary (anti-) diagonal** of the modified matrix `R = [[5, 7, 13], [9, 11, 19], [15, 17, 3]]`: - `i = 0`: `R[0][2] = 13` - `i = 1`: `R[1][1] = 11` - `i = 2`: `R[2][0] = 15` **2. Add the values:** $$\text{total} = 13 + 11 + 15 = 39$$ **Answer: 39**

Report a correction for Q19