3

Взял пример из книги на python 2(мб там все норм), в python 3 выводит ошибку, помогите найти:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]



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

    while low <= high:
        mid = (low + high)/2
        guess = lists[mid]
        guess = guess
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        if guess < item:
            low = mid + 1
        return None

print (binary_search(my_list, 2))

Ошибка:

Traceback (most recent call last): File "lesson.py", line 18, in print (binary_search(my_list, 2)) File "lesson.py", line 9, in binary_search guess = lists[mid] TypeError: list indices must be integers or slices, not float

1 ответ 1

6

В Python 2 эта строка mid = (low + high) / 2 вернёт вам целое число, а в Python 3 - вещественное. Очевидно, число вроде 2.5 не может служить для индексации списка, о чём и написано в ошибке. Исправить можно заменой оператора деления на оператор целочисленного деления - mid = (low + high) // 2.

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.