Binary search (python2.7) memo

From the book "Natoku! Algorithm" For memorandum


def binary_search(list, item):
    low = 0                               #Track the search part of the list using low and high
    high = len(list) - 1
    
    while low <= high:
        mid = (low + high) // 2
        guess = list[mid]          #Examine the element in the middle
        if guess == item:        #Detect item
            return mid     #If the answer is correct, mid(index)return it
        if guess > item:    #The number I guessed was too big
            high = mid -1
        else:                   #Was too small
            low = mid + 1
    return None    #If you can't find it, None

my_list = [1,3,5,7,9]

print binary_search(my_list, 3) #The answer is 3

2222222 # log2(100) = 7 log2 (100) is how many times 2 should be multiplied to get 100 The answer is 7

It turned out that the number of searches can be obtained by logarithmic conversion.

Recommended Posts

Binary search (python2.7) memo
Binary search in Python
[Python] Binary search ABC155D
Binary search with python
Binary search with Python3
Binary search in Python (binary search)
Python memo
python memo
Python memo
Binary search in Python / C ++
Algorithm in Python (binary search)
python memo
Python memo
Python memo
Python memo
Write a binary search in Python
[Python] Memo dictionary
python beginner memo (9.2-10)
python beginner memo (9.1)
visualize binary search
★ Memo ★ Python Iroha
ABC146C (binary search)
[Python] EDA memo
Python 3 operator memo
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
Python beginner memo (2)
[Python] Numpy memo
Algorithm learned with Python 10th: Binary search
Algorithm in Python (ABC 146 C Binary Search
Python class (Python learning memo ⑦)
My python environment memo
Sequential search with Python
python openCV installation (memo)
Python module (Python learning memo ④)
Visualization memo by Python
Python Exercise 1-Breadth-first search
[Python] Search (itertools) ABC167C
[Python] Binary Acing 2020D
Python test package memo
[Python] Memo about functions
[Python] Search (NumPy) ABC165C
python regular expression memo
[My memo] python -v / python -V
Python3 List / dictionary memo
[Memo] Python3 list sort
Python Tips (my memo)
[Python] Memo about errors
DynamoDB Script Memo (Python)
python bit full search
Linear search in Python
Python basic memo --Part 2
python recipe book Memo
Basic Python command memo
Python OpenCV tutorial memo
Search Twitter using Python
Python basic grammar memo
TensorFlow API memo (Python)
python useful memo links
Python decorator operation memo