Python如何实现的二分查找算法


Posted in Python onMay 27, 2020

先来看个用Python实现的二分查找算法实例

import sys 
def search2(a,m): 
 low = 0 
 high = len(a) - 1 
 while(low <= high): 
  mid = (low + high)/2
  midval = a[mid] 
   
  if midval < m: 
   low = mid + 1 
  elif midval > m: 
   high = mid - 1 
  else: 
   print mid 
   return mid 
 print -1
 return -1
if __name__ == "__main__": 
 a = [int(i) for i in list(sys.argv[1])] 
 m = int(sys.argv[2]) 
 search2(a,m)om/weixin.html#_labeldown

运行:

administrator@ubuntu:~/Python$ python test_search2.py 123456789 4

注:

1.'__':由于python的类成员都是公有、公开的被存取public,缺少像正统面向对象语言的私有private属性。

于是就用__来将就一下,模拟私有属性。这些__属性往往是内部使用,通常情况下不用改写。也不用读取。

加上2个下划线的目的,一是不和普通公有属性重名冲突,二是不让对象的使用者(非开发者)随意使用。

2.__name__ == "__main__"表示程序脚本是直接被执行的.

如果不等于表示脚本是被其他程序用import引入的.则其__name__属性被设为模块名

Python采用二分查找找出数字的下标

要考虑有重复数字的情况

class Solution(object):
 def searchRange(self, nums, target):
  """
  :type nums: List[int]
  :type target: int
  :rtype: List[int]
  def binary_search(start,end,value):
   while end>=start:
    mid = (start+end)//2
    print(mid)
    if nums[mid]>target:
     end = mid-1
    elif nums[mid]<target: start="mid+1" else:="" if="" value="=-1:" mid-1="">=start and nums[mid+value] == target:
       end = mid+value
      else:
       return mid
     else:
      if mid+1<=end and nums[mid+value] == target:
       start = mid+value
   return -1
  a=binary_search(0,len(nums)-1,-1)
  b=binary_search(0,len(nums)-1,1)
  return [a,b]
a = Solution()
l = [2,2]
print(a.searchRange(l,2))
 
</target:>

二分算法的定义不在多说了

import sys 
source = [1,2,3,4,5,6,7,8,9,10] #must be in order 
des = int(sys.argv[1]) 
low = 0
high = len(source) - 1
targetIndex = -1
print "des=",des 
while low <= high: 
 middle = (low + high)/2
 if des == source[middle]: 
  targetIndex = middle 
  break
 elif des < source[middle]: 
  high = middle -1
  print "middle element[index=",middle,",value=",source[middle],"] is bigger than des, continue search from[",low,"to",high,"]"
 else: 
  low = middle + 1
  print "middle element[index=",middle,",value=",source[middle],"] is smaller than des, continue search from[",low,"to",high,"]"
print "search complete, target element's index in source list is ",targetIndex

最后在分享一个

'fileName--BinarySearch.py'

src = [] 
def BinarySearch(low, high, target, *src): 
 '二分查找'
 while low <= high: 
  mid = (low + high) // 2
  midVal = src[mid] 
  if target < midVal: 
   high = mid - 1
  elif target > midVal: 
   low = mid + 1
  else: 
   return mid 
  BinarySearch(low, high, target, *src) 
print('Please input 10 number:') 
for number in range(10): 
 src.append(int(input('Num %d:' % number))) 
sortList = tuple(src) 
key = int(input('Please input key:')) 
location = BinarySearch(0, len(src) - 1, key, *sortList) 
if location != None: 
 print('Find target at %d' % (location + 1)) 
else: 
 print('No target!')

实例补充

#!/usr/bin/python env
# -*- coding:utf-8 -*-

def half_search(array,target):
 low = 0
 high = len(array) - 1
 while low < high:
   mid = (low + high)/2
   if array[mid] > target:
   high = mid - 1
   elif array[mid] < target:
   low = mid + 1
   elif array[mid] == target:
   print 'I find it! It is in the position of:',mid
   return mid
   else:
   print "please contact the coder!"
 return -1

if __name__ == "__main__":
 array = [1, 2, 2, 4, 4, 5]

运行结果如下:

I find it! It is in the position of: 4
4
-1
I find it! It is in the position of: 0
0
-1

以上就是Python如何实现的二分查找算法的详细内容,更多关于用Python实现的二分查找算法的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
浅谈Python中的闭包
Jul 08 Python
Python学生成绩管理系统简洁版
Apr 05 Python
python3安装pip3(install pip3 for python 3.x)
Apr 03 Python
浅谈python实现Google翻译PDF,解决换行的问题
Nov 28 Python
python linecache 处理固定格式文本数据的方法
Jan 08 Python
python实现广度优先搜索过程解析
Oct 19 Python
使用python 将图片复制到系统剪贴中
Dec 13 Python
keras 权重保存和权重载入方式
May 21 Python
python中if及if-else如何使用
Jun 02 Python
Python selenium键盘鼠标事件实现过程详解
Jul 28 Python
python list等分并从等分的子集中随机选取一个数
Nov 16 Python
Numpy中np.max的用法及np.maximum区别
Nov 27 Python
Python xml、字典、json、类四种数据类型如何实现互相转换
May 27 #Python
pycharm开发一个简单界面和通用mvc模板(操作方法图解)
May 27 #Python
Python列表如何更新值
May 27 #Python
Python模拟伯努利试验和二项分布代码实例
May 27 #Python
基于python纯函数实现井字棋游戏
May 27 #Python
Python实现读取并写入Excel文件过程解析
May 27 #Python
Python正则表达式如何匹配中文
May 27 #Python
You might like
php a simple smtp class
2007/11/26 PHP
ThinkPHP实现支付宝接口功能实例
2014/12/02 PHP
PHP 命名空间和自动加载原理与用法实例分析
2020/04/29 PHP
extjs grid取到数据而不显示的解决
2008/12/29 Javascript
使用jquery为table动态添加行的实现代码
2011/03/30 Javascript
利用NodeJS和PhantomJS抓取网站页面信息以及网站截图
2013/11/18 NodeJs
解决JQeury显示内容没有边距内容紧挨着浏览器边线
2013/12/20 Javascript
js opener的使用详解
2014/01/11 Javascript
AngularJS通过$http和服务器通信详解
2016/09/21 Javascript
vue实现tab切换外加样式切换方法
2018/03/16 Javascript
vue中使用sessionStorage记住密码功能
2018/07/24 Javascript
d3绘制基本的柱形图的实现代码
2018/12/12 Javascript
JavaScript基础之静态方法和实例方法分析
2018/12/26 Javascript
vue element-ui实现动态面包屑导航
2019/12/23 Javascript
js实现表单项的全选、反选及删除操作示例
2020/06/05 Javascript
详解vite2.0配置学习(typescript版本)
2021/02/25 Javascript
数据挖掘之Apriori算法详解和Python实现代码分享
2014/11/07 Python
python开发中range()函数用法实例分析
2015/11/12 Python
python数字图像处理之高级形态学处理
2018/04/27 Python
Python for循环中的陷阱详解
2018/07/13 Python
python中的插值 scipy-interp的实现代码
2018/07/23 Python
pytorch使用 to 进行类型转换方式
2020/01/08 Python
django中cookiecutter的使用教程
2020/12/03 Python
CSS3 Media Queries(响应式布局可以让你定制不同的分辨率和设备)
2013/06/06 HTML / CSS
英国女性时尚鞋类的潮流制造者:Koi Footwear
2018/10/19 全球购物
数控技术应届生求职信
2013/11/13 职场文书
12岁生日感言
2014/01/21 职场文书
先进德育工作者事迹材料
2014/01/24 职场文书
《罗布泊,消逝的仙湖》教学反思
2014/03/01 职场文书
采购意向书范本
2014/03/31 职场文书
媒矿安全生产承诺书
2014/05/23 职场文书
中职毕业生自我鉴定范文(3篇)
2014/09/28 职场文书
党性分析自查总结
2014/10/14 职场文书
党员干部廉洁自律承诺书
2015/04/28 职场文书
2015年公司国庆放假通知
2015/07/30 职场文书
2015年秋学期教研工作总结
2015/10/14 职场文书