【问题描述】完善Binary_search(lt)函数,实现二分查找功能。 【输入形式】输入待查找数列,和需要查找的数据。 【函数返回值】查找到返回True,未找到返回False. 【样例输入】 [4,6,7,9,45,78,87] 45 【样例输出】 找到该数
时间: 2023-12-03 08:03:54 浏览: 33
以下是实现二分查找的代码,你可以参考一下:
```python
def binary_search(lt, target):
"""
实现二分查找功能
:param lt: 待查找的有序数列
:param target: 需要查找的数据
:return: 查找到返回True,未找到返回False
"""
low = 0
high = len(lt) - 1
while low <= high:
mid = (low + high) // 2
if lt[mid] == target:
return True
elif lt[mid] < target:
low = mid + 1
else:
high = mid - 1
return False
# 测试代码
lt = [4, 6, 7, 9, 45, 78, 87]
target = 45
result = binary_search(lt, target)
if result:
print('找到该数')
else:
print('未找到该数')
```
输出结果为:
```
找到该数
```
相关问题
完善Binary_search(lt)函数,实现二分查找功能。 【输入形式】输入待查找数列,和需要查找的数据。 【函数返回值】查找到返回True,未找到返回False. 【样例输入】 [4,6,7,9,45,78,87] 45 【样例输出】 找到该数 def Binary_search(lt): low=0 high=len(lt)-1 flag=False lt=eval(input()) x=eval(input()) if Binary_search(lt)==True: print('找到该数') else: print('未找到该数')
完善的函数代码如下:
```
def Binary_search(lt, x):
low = 0
high = len(lt) - 1
while low <= high:
mid = (low + high) // 2
if lt[mid] == x:
return True
elif lt[mid] < x:
low = mid + 1
else:
high = mid - 1
return False
lt = eval(input())
x = eval(input())
if Binary_search(lt, x):
print('找到该数')
else:
print('未找到该数')
```
在这个函数中,我们通过输入数列 lt 和需要查找的数据 x,使用二分查找的方法在数列中找到 x,如果找到了就返回 True,否则返回 False。
python def binary_search(li,val):实现二分查找
好的,关于python的二分查找函数,我可以给您讲解实现的思路。二分查找是在有序数组中查找一个指定元素的算法,它通过比较中间元素和指定元素的大小关系,不断缩小查找的范围,直到找到目标元素或者确定目标元素不存在。在python中,我们可以通过递归或者循环的方式来实现二分查找。
下面是一个递归实现的python代码示例:
```
def binary_search(lst, val):
n = len(lst)
if n == 0:
return -1
mid = n // 2
if lst[mid] == val:
return mid
elif lst[mid] > val:
return binary_search(lst[:mid], val)
else:
result = binary_search(lst[mid+1:], val)
if result == -1:
return -1
else:
return mid+1+result
```
这个函数接受一个有序列表和一个待查找的元素作为输入,返回该元素在列表中的下标。如果该元素不存在于列表中,则返回-1。这个函数的时间复杂度是O(logn)。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)