GATE 2024 DA – Question 41
Consider the following Python function:
def fun(D, s1, s2):
if s1 < s2:
D[s1], D[s2] = D[s2], D[s1]
fun(D, s1+1, s2-1)What does this Python function fun() do? Select the ONE appropriate option below.
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (C) It reverses the list D between indices s1 and s2, both inclusive.
Explanation
**1. Follow one recursive call.** If s1 < s2, the simultaneous assignment swaps the entries at the two endpoints. The next call uses s1+1 and s2−1, leaving those endpoints fixed and working on the inner range.
**2. Follow the stopping condition.** When the indices meet or cross, no swap is performed. Thus every outer pair has been exchanged exactly once; a middle entry in an odd-length range stays in place.
**3. Identify the final effect.** For example, the range [a,b,c,d] becomes [d,b,c,a] and then [d,c,b,a]. Elements outside the supplied indices are untouched. **Answer: C — reverse the inclusive sublist in place.** It does more than one endpoint swap and performs no sorting comparisons.