zoukankan      html  css  js  c++  java
  • 二分查找算法


    """
    user:
    version:
    function:二分查找
    除法的运算
    '/' 无论是否整除返回的都是 float ,暂且叫它精确除法
    例如 : 10/5,的到的结果是 2.0
    '//' 无论是否整除返回的都是 int ,而且是去尾整除
    例如 :5//2,得到的结果是 2
    '%' 是取余运算,返回两个余数,经常在判断是否整除上运用
    例如 :5%2,得到的结果是 1

    向上向下取整(要先导入模块 math )
    向上取整
    math.ceil()
    返回值为 int
    向下取整
    math.floor()
    返回值为 int

    四舍五入
    内置函数 round()
    返回值为 int


    """
    import math

    def binary_search(list,item):
    low = 0
    high = len(list) - 1
    #print(high)

    while low <= high:
    mid = (low + high) / 2
    mid = math.floor(mid)
    guess = list[mid]
    if guess == item:
    return mid
    if guess > item:
    high = mid -1
    else:
    low = mid + 1
    #return None
    my_list = [1,3,5,7,9]
    print (binary_search(my_list,7))
    print (binary_search(my_list,-1))

  • 相关阅读:
    HTML
    python io
    python 线程进程
    python socket
    python 面向对象2
    python 面向对象
    python hashlib模块
    python configparser模块
    python logging模块
    数组去重方法汇总
  • 原文地址:https://www.cnblogs.com/51testing/p/12960284.html
Copyright © 2011-2022 走看看