简体   繁体   中英

Determine whether a number is in array of intervals

I'd like to perform a binary search for an element in array of intervals. For example, i need to find the index of the interval that includes 35 in intervals = [[1,10], [11, 18], [21, 24], [25, 32], [33, 40], [42, 43]] . Also, if the number is not found in any of intervals, the algorithm needs to return -1. Is that possible on python3? How can i modify my standard binary search function so it returns what i need? Here's what my binary search function looks like:

def b_search(array, element, start, end):
    if start > end:
        return -1
    mid = (start + end) // 2
    if element == array[mid]:
        return mid
    if element < array[mid]:
        return b_search(array, element, start, mid-1)
    else:
        return b_search(array, element, mid+1, end)

Thanks in advance.

You need to modify the binary search such that instead of checking if the element is equal to mid, you need to check whether the element is in the mid interval:

def b_search(array, element, start, end):
    if start > end:
        return -1
    mid = (start + end) // 2
    if array[mid][0] <= element <= array[mid][1]:
        return mid
    if element < array[mid][0]:
        return b_search(array, element, start, mid-1)
    return b_search(array, element, mid+1, end)
intervals = [[1,10], [11, 18], [21, 24], [25, 32], [33, 40], [42, 43]]
number = 50
idx_list = [i for i,interval in enumerate(intervals) if interval[0] <= number <= interval[1]]
idx = -1  if not idx_list else idx_list[0]
print(idx)

For binary search us the below code:

def b_search_2d(arr_2d, element, start=0, end=0):
    if end == 0:
        end = len(arr_2d) - 1
    if start > end:
        return -1
    mid = (start + end) // 2
    if arr_2d[mid][0] <= element <= arr_2d[mid][1]:
        return mid
    elif element < arr_2d[mid][0]:
        return b_search_2d(arr_2d, element, start, mid-1)
    else:
        return b_search_2d(arr_2d, element, mid+1, end)       
intervals = [[1,10], [11, 18], [21, 24], [25, 32], [33, 40], [42, 43]]
print(b_search_2d(intervals, 35))
print(b_search_2d(intervals, 50))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM