• Register
1 vote
194 views

Problem:

I wrote a program:

def only():
    names = ['Laia', 'Poter', 'Harrold', 'Annabell', 'Preety', 'Whina', 'Cory', 'Phase']

    put = input('Search with name:')
    binary_search(names, put)

    if position == -1:
        print("The name entered is not part of the list.")
    else:
        print(put, " 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

only()

But when I run this or compile this it shows:

Search with name:laia
Traceback (most recent call last):
  File "wanda.py", line 32, in <module>
    only()
  File "main.py", line 5, in only
    binary_search(names, put)
  File "main.py", line 22, in binary_search
    if names[middle] == entered:
TypeError: list indices must be integers or slices, not float

Why is this error happenning can anyone explain?

10 7 2
6,060 points

Please log in or register to answer this question.

2 Answers

1 vote
 
Best answer

Answer:

I think you should change the line

 middle = (first + last) / 2

To this line 

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

Or you can write your code like:

def only():
    names = ['Laia', 'Poter', 'Harrold', 'Annabell', 'Preety', 'Whina', 'Cory', 'Phase']

    put = input('Search with name:')
    binary_search(names, put)

    if position == -1:
        print("The name entered is not part of the list.")
    else:
        print(put, " 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

only()

I changed the line:

​This

 middle = (first + last) / 2

​To

​
 middle = (first + last) // 2

This

​

Happy coding.

11 6 4
34,950 points
0 votes

Solution:

It looks like you are using Python 3.x. One of the important differences in Python 3.x is the way division is handled. When you do x / y, an integer is returned in Python 2.x because the decimal is truncated (floor division). However in 3.x, the / operator performs 'true' division, resulting in a float instead of an integer (e.g. 1 / 2 = 0.5). What this means is that your are now trying to use a float to reference a position in a list (e.g. my_list[0.5] or even my_list[1.0]), which will not work as Python is expecting an integer. Therefore you may first want to try using middle = (first + last) // 2, adjusting so that the result returns what you expect. The // indicates floor division in Python 3.x.

I had this problem when using ANN and PyBrain on function testOnData().

So, I solved this problem putting "//" instead "/" inside the index on backprop.py source code.

Follow this below code

I Changed
print(('Max error:', 
    max(ponderatedErrors), 
    'Median error:',
     sorted(ponderatedErrors)[len(errors) / 2])) # <-- Error area 

To

print(('Max error:', 
    max(ponderatedErrors), 
    'Median error:',
     sorted(ponderatedErrors)[len(errors) // 2])) # <-- SOLVED. Truncated

you could also use:

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

For your code to work you should also set:

position = binary_search(names, entered)

 

10 6 4
31,120 points

Related questions

0 votes
1 answer 151 views
151 views
Problem: Hello! I am completely new to Python and trying to grasp concepts in Python. While I was learning lists and dictionaries, I wrote the following program: name = ["John", "Alice", "Catherine"] diction = {"name" : "Alice"} print(name[diction]) When I ... ; as a value and the program should print &ldquo;Alice&rdquo; on screen. I do not know what I have done wrong. Can anybody help?
asked Dec 18, 2020 Code Learner 9.8k points
0 votes
1 answer 44 views
3 votes
2 answers 468 views
468 views
Problem: I am trying to learn python3 and tuple. It was going pretty smooth unless I tried to access an element from a tuple of my program. It throws back an error: typeerror: tuple indices must be integers or slices, not tuple What's wrong? Any explanation?
asked Mar 25, 2020 Gavin 15.3k points
0 votes
1 answer 27 views
27 views
Problem: So, I'm not entirely sure what's going on here, but for whatever reason Python is throwing this at me. For reference, it's part of a small neural network I'm building for fun, but it uses a lot of np.array and such, so there's a lot of matrices ... type clash. Maybe somebody can help me figure this out, because I've been staring at this error for too long without being able to fix it.
asked Feb 16 Mashhoodch 13k points
1 vote
3 answers 709 views
709 views
Problem : I'm a newbie with Python's arrays and I don't understand how I can avoid below error: python typeerror: list indices must be integers or slices, not str
asked Oct 21, 2019 peterlaw 6.9k points
0 votes
1 answer 21 views
21 views
Problem: I've got two lists of coordinates, they look like this: list_kp2_ok: [[1185.60009765625, 933.6000366210938], [1310.4000244140625, 828.0000610351562], [1067.0, 979.0], [1310.0, 828.0], [1423.2000732421875, 814.800048828125], [1306.0, 828.0], [3634.0, 605.0 ... 828.6107788085938]] Now I need to check if there are any same coordinates on both lists and create a new list of them. So I wrote:
asked Feb 17 Mashhoodch 13k points
1 vote
1 answer 43 views
43 views
Problem: I have a program where I used tuple and it is throwing e some eror message. The code I worte is : import random board = [] for x in range(0,5): board.append(["O"] * 5) def print_board(board): for row in board: print " ".join(row) print_board(board) ... len(board)-1 or guess_col < 0 or guess_col > len(board[0])-1: TypeError: list indices must be integers not tuple How to solve this thing?
asked Apr 27, 2020 samhaz 5k points
0 votes
1 answer 4 views
4 views
Problem: Who can give me the solution of this topic I have got as a queston that indices must be integers or slices not float?
asked Apr 8 ashik 14.6k points
0 votes
1 answer 4 views
4 views
Problem: Any ideas on what I need to fix this?list indices must be integers or slices, not float
asked Apr 8 ashik 14.6k points
0 votes
1 answer 2 views
2 views
Problem: When running the code in IDLE gives the following error: Typeerror: slice indices must be integers or none or have an __index__ method. How to solve this?
asked Apr 21 muktaa 34.4k points