# -*- coding: utf-8 -*-

number_list = [0, 1, 2, 3, 4, 5, 6, 7]

def linear_search(value, iterable):
for index, val in enumerate(iterable):
if val == value:
return index
return -1 assert linear_search(5, number_list) == 5 def linear_search_v2(predicate, iterable):
for index, val in enumerate(iterable):
if predicate(val):
return index
return -1 assert linear_search_v2(lambda x: x == 5, number_list) == 5 def linear_search_recusive(array, value):
if len(array) == 0:
return -1
index = len(array)-1
if array[index] == value:
return index
return linear_search_recusive(array[0:index], value) assert linear_search_recusive(number_list, 5) == 5
assert linear_search_recusive(number_list, 8) == -1
assert linear_search_recusive(number_list, 7) == 7
assert linear_search_recusive(number_list, 0) == 0 def binary_search_recursive(sorted_array, beg, end, val):
if beg >= end:
return -1
mid = int((beg + end) / 2) # beg + (end-beg)/2
if sorted_array[mid] == val:
return mid
elif sorted_array[mid] > val:
return binary_search_recursive(sorted_array, beg, mid, val)
else:
return binary_search_recursive(sorted_array, mid+1, end, val) def test_binary_search_recursive():
a = list(range(10))
for i in a:
assert binary_search_recursive(a, 0, len(a), i) == i assert binary_search_recursive(a, 0, len(a), -1) == -1
assert binary_search_recursive(a, 0, len(a), 10) == -1

最新文章

  1. 【转】c3p0详细配置
  2. mssql 小技巧
  3. HTTP2.0的二进制分帧
  4. ubifs性能优化分析
  5. C#算法基础之冒泡排序
  6. tomcat server.xml配置详解
  7. 网易邮箱前端Javascript编码规范:基础规范
  8. bzoj 1093 [ZJOI2007]最大半连通子图(scc+DP)
  9. [Angular 2] @Input Custom public property naming
  10. Pick two points at random from the interior of a unit square, what is the expected distance between them?
  11. 深入Redis持久化
  12. [NewLife.XCode]实体列表缓存(最土的方法实现百万级性能)
  13. CentOS 7 (Linux) 下载百度网盘大文件
  14. AES-128-CBC加密
  15. Python——collections模块、time模块、random模块、os模块、sys模块
  16. OOP KLASSOOP, instanceklass
  17. ros service
  18. mogodb优化
  19. C# new override
  20. iOS获取/删除url中的参数

热门文章

  1. web端自动化——unittest框架编写web测试用例
  2. charles Windows 安装
  3. android基础---->数据保存到文件
  4. Net UI Spy工具:ManagedSpy
  5. docker 安装 tomcat8
  6. visual studio 2017搭建linux c++开发环境
  7. [一点感触]ADF4350 ADF4111混频记
  8. 修改 ubuntu NTFS 文件系统下没有执行权限的问题
  9. noip2019集训测试赛(二十一)Problem B: 红蓝树
  10. python 之 前端开发( DOM操作)