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实现DNS正向查询、反向查询的例子
Apr 25 Python
Python File(文件) 方法整理
Feb 18 Python
Python 列表去重去除空字符的例子
Jul 20 Python
用Python调用win命令行提高工作效率的实例
Aug 14 Python
python数据类型之间怎么转换技巧分享
Aug 20 Python
Python配置文件处理的方法教程
Aug 29 Python
Python多线程thread及模块使用实例
Apr 28 Python
你应该知道的Python3.6、3.7、3.8新特性小结
May 12 Python
利用scikitlearn画ROC曲线实例
Jul 02 Python
Ubuntu配置Pytorch on Graph (PoG)环境过程图解
Nov 19 Python
python3爬虫中多线程的优势总结
Nov 24 Python
Pytorch中使用ImageFolder读取数据集时忽略特定文件
Mar 23 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
收音机指标测试方法及仪器
2021/03/01 无线电
php 字符串中是否包含指定字符串的多种方法
2018/04/12 PHP
YII框架http缓存操作示例
2019/04/29 PHP
Whatever:hover 无需javascript让IE支持丰富伪类
2010/06/29 Javascript
中文字符串截取的js函数代码
2013/04/17 Javascript
javascript快速排序算法详解
2014/09/17 Javascript
js实现的动画导航菜单效果代码
2015/09/10 Javascript
jQuery仅用3行代码实现的显示与隐藏功能完整实例
2015/10/08 Javascript
JavaScript时间操作之年月日星期级联操作
2016/01/15 Javascript
使用递归遍历对象获得value值的实现方法
2016/06/14 Javascript
利用node.js写一个爬取知乎妹纸图的小爬虫
2017/05/03 Javascript
详解webpack 多入口配置
2017/06/16 Javascript
使用Node.js实现简易MVC框架的方法
2017/08/07 Javascript
webpack4打包vue前端多页面项目
2018/09/17 Javascript
详解微信小程序开发聊天室—实时聊天,支持图片预览
2019/05/20 Javascript
jquery实现自定义树形表格的方法【自定义树形结构table】
2019/07/12 jQuery
Vue实现base64编码图片间的切换功能
2019/12/04 Javascript
node实现mock-plugin中间件的方法
2019/12/25 Javascript
微信小程序indexOf的替换方法(推荐)
2020/01/14 Javascript
python发布模块的步骤分享
2014/02/21 Python
python 显示数组全部元素的方法
2018/04/19 Python
python3+PyQt5实现自定义窗口部件Counters
2018/04/20 Python
Python closure闭包解释及其注意点详解
2019/08/28 Python
深入浅析Python科学计算库Scipy及安装步骤
2019/10/12 Python
Python代码中如何读取键盘录入的值
2020/05/27 Python
Python logging日志模块 配置文件方式
2020/07/12 Python
Java的类与C++的类有什么不同
2014/01/18 面试题
学习委员自我鉴定
2014/01/13 职场文书
网上开商店的创业计划书
2014/01/19 职场文书
cf收人广告词大全
2014/03/14 职场文书
建设工地安全标语
2014/06/07 职场文书
乡镇党的群众路线教育实践活动个人整改方案
2014/10/31 职场文书
客房部经理岗位职责
2015/02/02 职场文书
赞助商致辞
2015/07/30 职场文书
幼儿园教学反思范文
2016/03/02 职场文书
Vue+Element UI实现概要小弹窗的全过程
2021/05/30 Vue.js