0

I'm using the binary search function mentioned here: When are bisect_left and bisect_right not equal?, but instead of returning False, I want to just skip values that aren't in the list e.

from bisect import bisect_left

def binsearch(l,e):
    index = bisect_left(l,e)
    if index == len(l) or l[index] != e:
        return False
    return index

l = [1, 2, 3, 6, 7, 8, 9]
e = [7, 9, 2, 4, 7]
index = []

for i in e:
   index.append(binsearch(l,i))

print index # [4, 6, 1, False, 4]

I tried replacing return False with pass but am getting the index of where the value not in the list would be placed. Is there a way to simply pass a value if it is not in l and output [4, 6, 1, 4]?

1 Answer 1

1

If you replace the return with a pass in the if statement, it's as if the if didn't exist. That's why you get an index returned.

What you can do instead is return either a sentinel value or a tuple combining the index with a True/False indicator of whether the item was found.

Sentinel style:

if index == len(l) or l[index] != e:
    return -1
return index

Tuple style:

if index == len(l) or l[index] != e:
    return False, None
return True, index

To complete the picture you need to put some logic into the spot where you're building the final list. Example for the tuple form:

for i in e:
    found, ind = binsearch(l,i)
    if found:
        index.append(ind)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.