Python如何實(shí)現(xiàn)的二分查找算法
先來看個(gè)用Python實(shí)現(xiàn)的二分查找算法實(shí)例
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
運(yùn)行:
administrator@ubuntu:~/Python$ python test_search2.py 123456789 4
注:
1.'__':由于python的類成員都是公有、公開的被存取public,缺少像正統(tǒng)面向?qū)ο笳Z言的私有private屬性。
于是就用__來將就一下,模擬私有屬性。這些__屬性往往是內(nèi)部使用,通常情況下不用改寫。也不用讀取。
加上2個(gè)下劃線的目的,一是不和普通公有屬性重名沖突,二是不讓對象的使用者(非開發(fā)者)隨意使用。
2.__name__ == "__main__"表示程序腳本是直接被執(zhí)行的.
如果不等于表示腳本是被其他程序用import引入的.則其__name__屬性被設(shè)為模塊名
Python采用二分查找找出數(shù)字的下標(biāo)
要考慮有重復(fù)數(shù)字的情況
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
最后在分享一個(gè)
'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!')
實(shí)例補(bǔ)充
#!/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]
運(yùn)行結(jié)果如下:
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如何實(shí)現(xiàn)的二分查找算法的詳細(xì)內(nèi)容,更多關(guān)于用Python實(shí)現(xiàn)的二分查找算法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python讀取和處理文件后綴為.sqlite的數(shù)據(jù)文件(實(shí)例講解)
下面小編就為大家?guī)硪黄狿ython讀取和處理文件后綴為.sqlite的數(shù)據(jù)文件(實(shí)例講解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
Python將視頻或者動(dòng)態(tài)圖gif逐幀保存為圖片的方法
本文是基于opencv將視頻和動(dòng)態(tài)圖gif保存為圖像幀的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-09-09
python中pyqtgraph知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于python中pyqtgraph知識(shí)點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-01-01
Python3.5 Pandas模塊之Series用法實(shí)例分析
這篇文章主要介紹了Python3.5 Pandas模塊之Series用法,結(jié)合實(shí)例形式分析了Python3.5中Pandas模塊的Series結(jié)構(gòu)原理、創(chuàng)建、獲取、運(yùn)算等相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2019-04-04
Python入門教程(十八)Python的For循環(huán)
這篇文章主要介紹了Python入門教程(十八)Python的For循環(huán),Python是一門非常強(qiáng)大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下2023-04-04

