用python实现折半查找_用Python实现的二分查找算法?

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

#!/usr/bin/env 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)

运行:

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]=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

else:

return mid

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))

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

'fileName--BinarySearch.py'最后在分享一个

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

原文至:https://www.py.cn/jishu/jichu/10384.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值