Complete the code to perform a linear search that returns the index of the target or -1 if not found.
def linear_search(arr, target): for i in range(len(arr)): if arr[i] == [1]: return i return -1
The function compares each element with the target. So, the blank should be target.
Complete the code to perform a binary search on a sorted list and return the index of the target or -1 if not found.
def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < [1]: low = mid + 1 else: high = mid - 1 return -1
We compare the middle element arr[mid] with the target to decide which half to search next.
Fix the error in the binary search code by completing the blank to correctly update the high pointer.
def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = [1] return -1
When the middle element is greater than the target, we move the high pointer to mid - 1 to search the left half.
Fill both blanks to create a dictionary comprehension that maps each word to its length only if the length is greater than 3.
words = ['apple', 'bat', 'carrot', 'dog'] lengths = {word: [1] for word in words if [2]
The dictionary maps each word to its length using len(word). The condition filters words with length greater than 3 using len(word) > 3.
Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is less than or equal to 5.
words = ['apple', 'bat', 'carrot', 'dog'] result = { [1]: [2] for word in words if [3] }
The dictionary keys are uppercase words using word.upper(). The values are lengths using len(word). The condition filters words with length less than or equal to 5 using len(word) <= 5.
