Answer the question
In order to leave comments, you need to log in
How does the code from the book "Groaming Algorithms" work?
Hello!
I started reading the book "Groaming Algorithms" and in the first example I can't understand how one of the lines works.
The code itself:
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = (low + high)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3))
print(binary_search(my_list, -1))
guess = list[mid]
Answer the question
In order to leave comments, you need to log in
In the first iteration
low = 0
high = 4
First you need to learn the language, and only then take on the algorithms.
Do you understand that there is a cycle? And every iteration guess will be different
def binary_search ( list, item) :
# в low и high хранятся границы части списка, где выполняется поиск
low = 0
high = len(list)-1
i = 0
# Пока не останется один элемент
while low <= high:
# Проверяем средний элемент
mid = (low + high)//2
guess = list[mid]
# Значение найдено
if guess == item:
return mid
# Значение велико
if guess > item:
high = mid - 1
# Значение мало
else:
low = mid + 1
# Значение не найдено
return None
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question