二分法:从一个只包含数字的list中查找某个数

复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/4/10 19:03
# @Author  : MnCu
# @Site    : 
# @File    : start.py
# @Software: PyCharm
import socket
import asyncio.coroutines
from tornado.web import Application
from tornado.web import RequestHandler
from tornado import ioloop
from tornado import gen


def b_s(li, num):
    bottom, top = 0, len(li)
    while bottom < top:
        mid = int((top + bottom)/2)
        if li[mid] > num:
            top = mid - 1
        elif li[mid] < num:
            bottom = mid + 1
        else:
            return mid
    return bottom if li[bottom] == num else False
def binary_search(num, li):
    bottom, top = 0,len(li) - 1
    while bottom < top:
        mid = int((bottom + top)/2)
        if mid == bottom:
            break
        if num < li[mid]:
            top = mid
        elif num > li[mid]:
            bottom = mid
        else:
            return mid
    return bottom if li[bottom] == num else False

l = [1, 4, 12, 45, 66, 99, 120, 444, 456]
print(b_s(l, 1))
复制代码
原文地址:https://www.cnblogs.com/yezuhui/p/6863687.html