Complete the code to count inversions by comparing pairs.
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]))
We count an inversion when a number is greater than a number that comes after it.
Complete the code to merge two sorted halves and count split inversions.
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
We pick from left if left[i] is less than right[j] to keep order.
Fix the error in the recursive function to count inversions using merge sort.
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])
We add counts from left, right, and split inversions to get total.
Complete the code to create a dictionary of word lengths for words longer than 3 letters.
words = ['apple', 'bat', 'carrot', 'dog', 'elephant'] lengths = {word: len(word) for word in words if len(word) [1] 3} print(lengths)
Use ':' to map word to length, and '>' to filter words longer than 3.
Fill all three blanks to create a filtered dictionary with uppercase keys and values greater than 0.
data = {'a': 1, 'b': -2, 'c': 3}
result = [1]: [2] for k, v in data.items() if v [3] 0}}
print(result)Keys are uppercase k, values are v, and filter keeps values > 0.
