首页 > 编程语言 > 详细

Python面试常用算法

时间:2019-08-27 22:10:14      阅读:91      评论:0      收藏:0      [点我收藏+]

查找算法

二分查找

import doctest

def binary_search(alist, item):
    """
    >>> alist=[1,3,4,7,11,18,29]
    >>> binary_search(alist,1)
    0
    >>> binary_search(alist,7)
    3
    >>> binary_search(alist,18)
    5
    >>> binary_search(alist,31)

    """

    binary_index = int(len(alist)/2)
    if alist == []:
        return None
    elif alist[binary_index] > item:
        return binary_search(alist[:binary_index], item)
    elif alist[binary_index] < item:
        result = binary_search(alist[binary_index + 1:], item)
        return  None if result is None else result + binary_index + 1
    elif alist[binary_index] == item:
        return binary_index

if __name__ == "__main__":
    doctest.testmod(verbose=True)

 

Python面试常用算法

原文:https://www.cnblogs.com/plyonfly/p/11420955.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!