I'm creating a simple binary search algorithm and I keep getting this error:
'int' not subscriptable
while not found and firstPos <= lastPos:
midPos = (int(firstPos + lastPos)/2)
if searchNumber == lastPos[midPos]:
found = True
else:
if searchNumber < lastPos[midPos]:
lastPos = midPos - 1
else:
firstPos = midPos + 1
The issue is in the code:
lastPos[midPos]
Here lastPos is a number. It is not possible to subscript a number. According to your logic your code should be something like:
if searchNumber == data[midPos]:
found = True
else:
if searchNumber < data[midPos]:
lastPos = midPos - 1
else:
firstPos = midPos + 1
This is assuming, the array you are searching is named data . Use whatever your array name is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.