简体   繁体   中英

In python, how can i make a binary search function with range and some conditions

The biggest problem for me is to express the value of mid according to the range. plz I need a help Even if it's not a perfect answer, I need a hint. I don't even know if the reason I'm having a hard time is that Python is awkward or that I'm stupid.

def bsearch(ss, x):        #just call bsearch_range
    return bsearch_range( ss, x, range(len(ss)) )

def bsearch_range(ss, x, r):    #ss is list, r=range(len(ss))
  left,right=0,0
  while len(r)>0:
    mid= (r.start+(r.stop-1)) // 2
    if ss[mid]==x:
      left,right=mid,mid+1
      return range(left,right)
    elif x<ss[mid]:
      right=right-1

    else:
      left=left+1
  return range(left,right)

First. The bsearch function is a binary search function that tells you the range you want to find in range.

Second. Lists are sorted and may contain duplicate numbers. For example) list ss=[1,2,2,2,3,6]

So. If duplicate elements exist in the list, we need to express the range of duplicate elements. For example) list ss[1,2,2,2,3,6], bsearch(ss,2)==range(1,4)

Third. If the element you want to find does not exist in the list, you should be able to tell the place where it should be in range. For example) ss[1,2,2,2,3,6] bsearch(ss,7)==range(6,6)

Looking at your code, I believe you did not fully understand how the "normal" binary search algorithm works. (What is r for? It does not change throughout the loop body, so the while loop goes on forever...)

As a hint, this is what binary search in Python looks like:

def bi_search_left(array: list[int], x: int) -> int:
    a, b = 0, len(array)
    while a < b:
        mid = (a + b) // 2
        if array[mid] < x:
            a = mid + 1
        else:
            b = mid
    return a

Notice, the name of the function is bi_search_left . That is because it returns the index of the leftmost element matching the value of the x parameter. (Actually, it returns the index at which x needs to be inserted in in order for it to become the first element in the list with this value, so it also works for empty lists.)

By changing the function just a tiny bit, you could get bi_search_right , which, as the name says, returns the rightmost index. Combining these two methods could get you the desired result.

I think that was enough of a hint:)

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