Search code examples
python-3.xbinary-search

In Python3, the classic mid = start + (end - start) / 2 throws TypeError: list indices must be integers or slices, not float


In Python3,

The classic binary search first step mid = start + (end - start) / 2 throws TypeError: list indices must be integers or slices, not float because division yeilds float instead of int by default.

Is there a better way to deal with this than doing int(mid)?


Solution

  • In Python 3, the / operator does floating-point division, even if it's between two integers.

    You want // instead, which will perform integer division.