請編寫乙個二進位制搜尋功能,該功能可以搜尋已排序列表中的專案。 該函式應返回列表中要搜尋的元素的索引。
import math
defbinary_search
(li, element)
: bottom =
0 top =
len(li)-1
index =-1
while top >= bottom and index ==-1
: mid =
int(math.floor(
(top + bottom)
/2.0))
# 二分查詢
if li[mid]
== element:
index = mid
elif li[mid]
> element:
top = mid -
1else
: bottom = mid +
1return index
li =[1
,2,3
,4,5
,7,8
,9]print
(binary_search(li,1)
)
二分查詢是一種快速查詢的方法,值得去學習 Python小練習三
給出下列文件,但求使用者可以不使用者文字編輯器的情況下修改配置文件 1.只修改backend的配置就可以 2.使用者需要輸入backend,在輸入網域名稱 最後輸入具體配置 the key input 請輸入需要修改的標識1 the value input 請輸入需要修改的標識2 the conte...
python2 7練習小例子(三)
3 題目 乙個整數,它加上100後是乙個完全平方數,再加上168又是乙個完全平方數,請問該數是多少?程式分析 假設該數為 x。1 則 x 100 n2,x 100 168 m2。2 計算等式 m2 n2 m n m n 168。3 設定 m n i,m n j,i j 168,i 和 j 至少乙個是...
python練習小程式
1.今年是否為閏年 import time thisyear time.localtime 0 print time.localtime if thisyear 400 0 or thisyear 4 0 and thisyear 100!0 print this year s is leap ye...