python - Python散列二分搜索
问题描述
编写一个 binary_search 函数,该函数在每一步都打印正在搜索的列表,如下面的输出所示。它显示了当前正在搜索的子列表以及如何将其拆分为围绕中点的两部分。
这是我尝试过的,但仍然很难找到解决方案:
def binary_search(a_list, item):
print(a_list) # just to show the search area
if a_list == []:
return False
midpoint = len(a_list) // 2
element = a_list[midpoint]
if item == element:
return True
elif item < element: # first half
return binary_search(a_list[:midpoint], item)
else:
return binary_search(a_list[midpoint + 1:], item)
给定输入:
test_list = [0,1,2,8,13,17,19,32,42]
binary_search(test_list,3)
binary_search(test_list,13)
预期输出:
[0, 1, 2, 8, 13, 17, 19, 32, 42]
[0, 1, 2, 8] 13 [17, 19, 32, 42]
[0, 1, 2, 8]
[0, 1] 2 [8]
[8]
[] 8 []
[]
[0, 1, 2, 8, 13, 17, 19, 32, 42]
[0, 1, 2, 8] 13 [17, 19, 32, 42]
解决方案
您需要将列表打印到元素的左侧和右侧,试一试:
def binary_search(a_list, item):
print(a_list)
if a_list == []:
return False
midpoint = len(a_list) // 2
element = a_list[midpoint]
left = a_list[:midpoint]
right = a_list[midpoint+1:]
print(left,element,right )
if item == element:
return True
elif item < element: # first half
return binary_search(left, item)
else:
return binary_search(right, item)
输入:
test_list = [0,1,2,8,13,17,19,32,42]
binary_search(test_list,3)
输出:
[0, 1, 2, 8, 13, 17, 19, 32, 42]
[0, 1, 2, 8] 13 [17, 19, 32, 42]
[0, 1, 2, 8]
[0, 1] 2 [8]
[8]
[] 8 []
[]
推荐阅读
- php - Laravel 政策:项目中没有使用,只有 403
- vue.js - Vue 按月过滤的对象数组
- javascript - 澄清while循环中的逻辑语句AND和OR
- javascript - 使用 Promises 处理页面加载
- rabbitmq - RabbitMQ 直接交换,有路由键,没有队列或订阅者,这对性能好吗?
- node.js - 如何检查节点快递应用程序中是否存在数据
- visual-studio - 通过 csproj 文件中的 msbuild 目标在 Visual Studio 2019 输出窗口中显示消息?
- php - edit.blade.php 没有读取我的变量
- java - 在两个单独的 JavaFx TextArea 中显示两个不同线程的输出
- javascript - 如何解构此反应组件中的对象状态数组以使用单个字段数据