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)
Instead of simulating every pass step by step, use a shortcut: each call to fun does one left-to-right bubble pass, and every time it swaps two adjacent elements, it fixes exactly one "inversion" (a pair of positions where the earlier element is bigger than a later element). Running enough passes to fully sort a 5-element list means every inversion gets fixed exactly once across all the passes, so the total count printed at the end equals the number of inversions present in the original array.
First count the inversions in the starting array $[5, 3, 4, 1, 2]$. An inversion is any pair of positions $(i, j)$ with $i < j$ where the value at $i$ is bigger than the value at $j$. Check every pair:
That gives 8 inversions out of the 10 possible pairs.
Now check that 5 passes is really enough to clear all of them. A single left-to-right bubble pass is guaranteed to move the largest remaining unsorted element all the way to its correct position at the far right. With 5 elements, at most 4 passes are ever needed to fully sort the list, and the loop here runs 5 passes, one more than needed. So by the time all 5 calls to fun finish, the list is completely sorted and every one of the 8 original inversions has been resolved by exactly one adjacent swap.
Since each swap adds exactly 1 to count and there are 8 swaps in total across the 5 passes, count ends at 8, and that is what print(count) outputs.
$$\boxed{8}$$