The GATE Grind

GATE 2024 DA – Question 41

Programming, Data Structures and Algorithms · Programming in Python · 2 marks · Multiple choice

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.

  1. It finds the smallest element in D from index s1 to s2, both inclusive.
  2. It performs a merge sort in-place on this list D between indices s1 and s2, both inclusive.
  3. It reverses the list D between indices s1 and s2, both inclusive.
  4. It swaps the elements in D at indices s1 and s2, and leaves the remaining elements unchanged.

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.

More Programming in Python questions

All Programming in Python questions →