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

The function swaps the elements at the two ends of the range, then moves both indices towards the middle and repeats. Swapping the outer pairs one after another reverses the sublist between s1 and s2.