python-二分法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-二分法相关的知识,希望对你有一定的参考价值。

二分法适用于对大数据进行查找
例如:

def find(list1,finded):
middle=int(len(list1)/2)
if len(list1)>=1:
if finded>list1[middle]:
list1[middle:]
print(list1[middle:])
find(list1[middle:],finded)
if finded<list1[middle]:
list1[:middle]
print(list1[:middle])
find(list1[:middle], finded)
if finded==list1[middle]:
print(list1[middle])
else:
print(‘未找到!‘)
return
if __name__==‘__main__‘:
a=list(range(1,600,3))
find(a,400)

结果:

[301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379, 382, 385, 388, 391, 394, 397, 400, 403, 406, 409, 412, 415, 418, 421, 424, 427, 430, 433, 436, 439, 442, 445, 448, 451, 454, 457, 460, 463, 466, 469, 472, 475, 478, 481, 484, 487, 490, 493, 496, 499, 502, 505, 508, 511, 514, 517, 520, 523, 526, 529, 532, 535, 538, 541, 544, 547, 550, 553, 556, 559, 562, 565, 568, 571, 574, 577, 580, 583, 586, 589, 592, 595, 598]
[301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379, 382, 385, 388, 391, 394, 397, 400, 403, 406, 409, 412, 415, 418, 421, 424, 427, 430, 433, 436, 439, 442, 445, 448]
[376, 379, 382, 385, 388, 391, 394, 397, 400, 403, 406, 409, 412, 415, 418, 421, 424, 427, 430, 433, 436, 439, 442, 445, 448]
[376, 379, 382, 385, 388, 391, 394, 397, 400, 403, 406, 409]
[394, 397, 400, 403, 406, 409]
[394, 397, 400]
[397, 400]
400

 






























以上是关于python-二分法的主要内容,如果未能解决你的问题,请参考以下文章

python学习(二分法)

Python 二分法查找

python实现二分法查找

二分法查找python的实现

Python 二分法查找

python-二分法