在 python 3.7 中学习二进制搜索
Learning Binary Search in python 3.7
我在 https://www.geeksforgeeks.org/binary-search/
上找到了这段代码
# Python Program for recursive binary search.
# Returns index of x in arr if present, else -1
def binarySearch (arr, l, r, x):
# Check base case
if r >= l:
mid = l + (r - l)/2;
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it
# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
# Else the element can only be present
# in right subarray
else:
return binarySearch(arr, mid+1, r, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40, 50, 80, 140, 200, 2000, 100]
x = 50
# Function call
result = binarySearch(arr, 0, len(arr)-1, int)
if result != -1:
print ("Element is present at index %d" % result)
else:
print ("Element is not present in array")
但是,当我 运行 它时,我遇到了这个问题:TypeError: list indices must be integers or slice, not float
我不确定如何转换。我试图将整个数组设置为一个 int 但没有用,或者用 int 替换 x 也没有用。
有什么建议吗?
问题出在这一行:
mid = l + (r - l)/2;
In Python 3 / 进行浮点除法并且由于 mid 用作数组索引,因此需要一个整数。要进行整数除法,请使用 //
mid = l + (r - l) // 2;
函数的调用还有一个问题:
result = binarySearch(arr, 0, len(arr) - 1, int)
最后一个参数不应该是int而是x(你要搜索的变量):
result = binarySearch(arr, 0, len(arr) - 1, x)
当你传入 int 作为最后一个参数时,你会得到一个错误 TypeError: unorderable types: int() > type()
我在 https://www.geeksforgeeks.org/binary-search/
上找到了这段代码# Python Program for recursive binary search.
# Returns index of x in arr if present, else -1
def binarySearch (arr, l, r, x):
# Check base case
if r >= l:
mid = l + (r - l)/2;
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it
# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
# Else the element can only be present
# in right subarray
else:
return binarySearch(arr, mid+1, r, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40, 50, 80, 140, 200, 2000, 100]
x = 50
# Function call
result = binarySearch(arr, 0, len(arr)-1, int)
if result != -1:
print ("Element is present at index %d" % result)
else:
print ("Element is not present in array")
但是,当我 运行 它时,我遇到了这个问题:TypeError: list indices must be integers or slice, not float 我不确定如何转换。我试图将整个数组设置为一个 int 但没有用,或者用 int 替换 x 也没有用。
有什么建议吗?
问题出在这一行:
mid = l + (r - l)/2;
In Python 3 / 进行浮点除法并且由于 mid 用作数组索引,因此需要一个整数。要进行整数除法,请使用 //
mid = l + (r - l) // 2;
函数的调用还有一个问题:
result = binarySearch(arr, 0, len(arr) - 1, int)
最后一个参数不应该是int而是x(你要搜索的变量):
result = binarySearch(arr, 0, len(arr) - 1, x)
当你传入 int 作为最后一个参数时,你会得到一个错误 TypeError: unorderable types: int() > type()