首页 > 代码库 > python-二分法
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-二分法