0
0
DSA Pythonprogramming~10 mins

Count Inversions in Array in DSA Python - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to count inversions by comparing pairs.

DSA Python
def count_inversions(arr):
    count = 0
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            if arr[i] [1] arr[j]:
                count += 1
    return count

print(count_inversions([2, 4, 1, 3, 5]))
Drag options to blanks, or click blank then click option'
A>
B<
C==
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' causes counting non-inversions.
Using '==' counts equal pairs, which is incorrect.
2fill in blank
medium

Complete the code to merge two sorted halves and count split inversions.

DSA Python
def merge_count(left, right):
    i = j = 0
    merged = []
    count = 0
    while i < len(left) and j < len(right):
        if left[i] [1] right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            count += len(left) - i
            j += 1
    merged += left[i:]
    merged += right[j:]
    return merged, count
Drag options to blanks, or click blank then click option'
A>
B<
C<=
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' causes wrong merge order.
Using '>=' or '<=' can cause incorrect counting.
3fill in blank
hard

Fix the error in the recursive function to count inversions using merge sort.

DSA Python
def sort_count(arr):
    if len(arr) <= 1:
        return arr, 0
    mid = len(arr) // 2
    left, left_count = sort_count(arr[:mid])
    right, right_count = sort_count(arr[mid:])
    merged, split_count = merge_count(left, right)
    return merged, left_count [1] right_count + split_count

print(sort_count([2, 3, 8, 6, 1])[1])
Drag options to blanks, or click blank then click option'
A+
B*
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' subtracts counts incorrectly.
Using '*' or '/' causes wrong results.
4fill in blank
hard

Complete the code to create a dictionary of word lengths for words longer than 3 letters.

DSA Python
words = ['apple', 'bat', 'carrot', 'dog', 'elephant']
lengths = {word: len(word) for word in words if len(word) [1] 3}
print(lengths)
Drag options to blanks, or click blank then click option'
A:
B>
C<
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of ':' in dictionary comprehension.
Using '<' instead of '>' in filter condition.
5fill in blank
hard

Fill all three blanks to create a filtered dictionary with uppercase keys and values greater than 0.

DSA Python
data = {'a': 1, 'b': -2, 'c': 3}
result = [1]: [2] for k, v in data.items() if v [3] 0}}
print(result)
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' filters wrong values.
Using k instead of k.upper() keeps keys lowercase.