Complete the code to find the first occurrence of the target in the sorted array.
def first_occurrence(arr, target): low, high = 0, len(arr) - 1 result = -1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: result = mid high = mid [1] elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return result
When the target is found, to find the first occurrence, we move the high pointer to mid - 1 to continue searching in the left half.
Complete the code to find the last occurrence of the target in the sorted array.
def last_occurrence(arr, target): low, high = 0, len(arr) - 1 result = -1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: result = mid low = mid [1] elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return result
When the target is found, to find the last occurrence, we move the low pointer to mid + 1 to continue searching in the right half.
Fix the error in the code to correctly count occurrences of the target in the sorted array.
def count_occurrences(arr, target): first = first_occurrence(arr, target) if first == -1: return 0 last = last_occurrence(arr, target) return last - first [1] 1
The count of occurrences is last index minus first index plus one.
Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.
words = ['apple', 'bat', 'carrot', 'dog', 'elephant'] lengths = {word: [1] for word in words if len(word) [2] 3}
We want the length of each word as the value and only include words longer than 3 characters.
Fill all three blanks to create a dictionary with uppercase keys, values as word lengths, and only words longer than 3 characters.
words = ['apple', 'bat', 'carrot', 'dog', 'elephant'] lengths = [1]: [2] for word in words if len(word) [3] 3}
Keys are uppercase words, values are their lengths, and only words longer than 3 are included.
