GATE DA 2024 · Programming in Python

MCQ · 2 marks · Problem PROG-PYTH-0011

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. A
    It finds the smallest element in D from index s1 to s2, both inclusive.
  2. B
    It performs a merge sort in-place on this list D between indices s1 and s2, both inclusive.
  3. C
    It reverses the list D between indices s1 and s2, both inclusive.
  4. D
    It swaps the elements in D at indices s1 and s2, and leaves the remaining elements unchanged.

Solve it on GATE DA practice →More Python Programming problems

Show the worked solutionEach call swaps the two end elements D[s1] and D[s2] and then recurses on the inner part (s1+1 to s2-1). It stops when the two indices meet or cross.So D[s1] and D[s2] are swapped, then D[s1+1] and D[s2-1], and so on: the part of D from index s1 to s2 is reversed.Example: D = [1, 2, 3, 4, 5], fun(D, 1, 3) gives [1, 4, 3, 2, 5].Answer: C

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com