TypeError: list indices must be integers or slices, not float in Python

Dung Do Tien Sep 07 2021 184

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have a small assignment, I write a small project help me find some user existed in an array, I want to apply binary search algorithm to help me search faster. Like this:

position = 0
def main():
    names = ['A Name', 'B Name', 'C meah', 'D Name',
             'E Name', 'G Name', 'M Fullname',
             'Ross Name', 'Sasha Name', 'Xavier Name']

    entered = input('Enter name to search:')
    binary_search(names, entered)

    if position == -1:
        print("Name entered is not found.")
    else:
        print(entered, " is part of the list and is number ", position, " on the list.")
    input('Press<enter>')

def binary_search(names, entered):
    first = 0
    last = len(names) - 1
    position = -1
    found = False

    while not found and first <= last:
        middle = (first + last) / 2

        if names[middle] == entered:
            found = True
            position = middle
        elif names[middle] > entered:
            last = middle - 1
        else:
            first = middle + 1

    return position

main()

But I get an exception TypeError: list indices must be integers or slices, not float when I run code above.

Enter name to search:A Name
Traceback (most recent call last):
  File "main.py", line 35, in <module>
    main()
  File "main.py", line 8, in main
    binary_search(names, entered)
  File "main.py", line 25, in binary_search
    if names[middle] == entered:
TypeError: list indices must be integers or slices, not float

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • Y

    Yusuf Bashir Sep 07 2021

    This error throw is related to set an index to get an item from an array.

    You need to change the line code below:

    middle = (first + last) / 2

    To

    middle = int((first + last) / 2)

    And it resolved for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close