IAE Academy

GATE 2026 DA Q.58: solution and answer

GATE 2026 · DAQ.58 · 2 marks · NAT

Consider the given Python program.

def fun(L, i=0):
      if i >= len(L)-1:
            return 0
      if L[i] > L[i+1]:
            L[i+1], L[i] = L[i], L[i+1]
            return 1+fun(L, i+1)
      else:
            return fun(L, i+1)
data = [5, 3, 4, 1, 2]
count = 0
for _ in range(len(data)):
      count += fun(data)
print(count)

The output of the program is ________ . (Answer in integer)

See the question in the paper

Answer and solution

ANSWER

The program prints 8.

Official answer: 8Source: Official answer key, GATE 2026 DA (IIT Guwahati)

  1. Each call fun(data) starts with i=0 and walks i up to len(L)-2 = 3. At each i, if L[i] > L[i+1] it swaps the pair and adds 1 to the result. The swap line L[i+1], L[i] = L[i], L[i+1] evaluates the right side first, so it is a true swap. One call is therefore one bubble-sort pass, and it returns the number of swaps made. data is the same list object every time, so each call sees the result of the previous one.

  2. The loop runs len(data) = 5 times, so count is the sum of the swap counts of 5 passes.

  3. Pass 1 on [5, 3, 4, 1, 2]: 5 > 3 swaps to [3, 5, 4, 1, 2]; 5 > 4 swaps to [3, 4, 5, 1, 2]; 5 > 1 swaps to [3, 4, 1, 5, 2]; 5 > 2 swaps to [3, 4, 1, 2, 5]; at i = 4 the base case returns 0. The pass returns 4.

  4. Pass 2 on [3, 4, 1, 2, 5]: 3 < 4 no swap; 4 > 1 swaps to [3, 1, 4, 2, 5]; 4 > 2 swaps to [3, 1, 2, 4, 5]; 4 < 5 no swap. The pass returns 2.

  5. Pass 3 on [3, 1, 2, 4, 5]: 3 > 1 swaps to [1, 3, 2, 4, 5]; 3 > 2 swaps to [1, 2, 3, 4, 5]; the remaining pairs are in order. The pass returns 2.

  6. Passes 4 and 5 act on the sorted list [1, 2, 3, 4, 5], so no swap happens and each returns 0.

  7. Total: , so the program prints 8.

  8. Check: every bubble-sort swap removes exactly one inversion, and 5 passes are enough to sort 5 elements, so the total number of swaps equals the number of inversions of the original list. In , 5 is above 4 later elements, 3 is above 2 (1 and 2), 4 is above 2 (1 and 2), and 1 is above none. That gives .

KEY IDEA

fun is one bubble-sort pass that returns its swap count, and the loop makes 5 passes on the same mutated list. The total is the number of inversions of the original list: .

WATCH OUT FOR

Treating each call as acting on a fresh copy of [5, 3, 4, 1, 2], which would give . The list is mutated in place and the loop passes the same object every time. Another slip is stopping after the first pass (4) and forgetting that later passes still swap.

From the GATE 2026 DA paper. Every question of this paper · Download the full paper · All 10 Python questions, with notes

More Python questions