简体   繁体   中英

Python - Binary search to find elements of a list that match the index?

So I want to search a list using binary search, and find elements of the list that have a value that matches the index number. For example, if my list contains a 2 at index 2, I want to print that value. It has to work with multiple values as well. Here is what I have so far for a binary search:

alist=[4,5,7,9,13,45,34,58,99,125,145]
key=145
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
    mid = (start + end)//2
    if alist[mid] > key:  # this is where we check if the guess is bigger than the key
            end = mid
    elif alist[mid] < key:
            start = mid + 1
    elif alist[mid] == key:
                print (f"you searched for {alist[mid]} and we found it in the index number {alist.index(125)} of the list")
                break
else:
    print ("Not Found!")

This will only work with a key. I'm new to python and wondering how I would go about implementing this.

If I am understanding you correctly, I think this should work for your print statement:

print("you searched for {} and we found it in the index number {} of the list".format(key, mid))

If you only want to print it when the index is the same as the value you can just add an if statement:

if key == mid:
    print("you searched for {} and we found it in the index number {} of the list".format(key, mid))

Does this answer your question?

If I'm understanding your problem correctly, you want to find the elements that have same value as their index number then you have to traverse the list and print the elements using condition print([i for i in alist if i==alist.index(i)])

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