'Why display my list index out of range
i am coding binary search, I define a function ,and have 4 parameter, one of the parameter that number is the number you want to search ,but when i input a big number which bigger than the last number of list ,the compiler will display the list index out of range, what is the connection between number and index?
list = [2, 3, 4, 6, 8, 9, 10, 11, 20]
mid = len(list) / 2
left = 0
right = len(list)
def searchNumber(left, right, number, mid):
while left <= right:
mid = (right - left) / 2 + left
if list[mid] == number:
print("the local is in %d" % (mid))
return mid
break
elif list[mid] > number:
right = mid - 1
else:
left = mid + 1
Solution 1:[1]
list = [2, 3, 4, 6, 8, 9, 10, 11, 20]
mid = len(list) / 2
left = 0
right = len(list)
def searchNumber(left, right, number, mid):
**while left < right:**
mid = (right - left) / 2 + left
if list[mid] == number:
print("the local is in %d" % (mid))
return mid
break
elif list[mid] > number:
right = mid - 1
else:
left = mid + 1
Solution 2:[2]
I ran this code,
list = [2, 3, 4, 6, 8, 9, 10, 11, 20]
mid = len(list) / 2
left = 0
right = len(list)
def searchNumber(left, right, number, mid):
while left <= right:
mid = (right - left) / 2 + left
if list[mid] == number:
print("the local is in %d" % (mid))
return mid
break
elif list[mid] > number:
right = mid - 1
else:
left = mid + 1
return None
a = searchNumber(0, len(list)-1, 40, 40)
print "a =" + str(a)
b = searchNumber(0, len(list)-1, 9, 5)
print "b =" + str(b)
I got correct output in both the cases, where the asked number is present and the asking number is larger than the largest number of the list.
$ python pyt.py
a = None
the local is in 5
b = 5
I suspect the Error you get is because you're passing number which is negative or bigger than length-1 of the array, I don't see any other cases where you'll get "index out of range" Error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suraj Dubal |
Solution 2 | Nimantha |