Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I found a mistake in the book "Grokking Algorithms"

Tags:

python

I am beginner in programming. I am reading the book "Grokking algorithms" by Aditya Y Bhargava." And in the first code I found a mistake. The book describes binary algorithm. It says that the algorithm must takes the average of an array and then average of that average, but I debbuged the code and it just takes a very big number of array and then reduces it by 1. Maybe it is a difference between versions, because I use Python 3.7, but in the book it is Python 2.7

def binary_search(list, item):
    low = 0
    high = len(list)-1

    while low <= high:
        mid = int(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, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(binary_search(my_list, 1))
like image 515
Fr33m4n_VL Avatar asked Oct 07 '19 15:10

Fr33m4n_VL


1 Answers

The errata for the book lists this as an error. It should be:

mid = (low + high) // 2

So: good catch!

And, spoiler alert: there are more errors!

like image 69
kwinkunks Avatar answered Nov 11 '22 22:11

kwinkunks