zoukankan      html  css  js  c++  java
  • python学习--bisect模块

    1. 模块介绍

    1. bisect模块为内置标准库,它实现了二分法查找算法(只要提到二分法查找,应该优先想到此模块)

    2. 主要包含有两个函数:bisect函数(查找元素)和insort函数(插入元素)。

    2. 常用方法介绍

    场景1:已知一个有序列表,查找目标元素的位置索引

    import bisect
    
    # 已知一个有序序列
    ordered_list = [23, 34, 59, 78, 99]
    
    des_element = 21
    res = bisect.bisect(ordered_list, des_element)
    print(res)  # res: 0
    
    des_element = 35
    res = bisect.bisect(ordered_list, des_element)
    print(res)  # res: 2
    View Code

    说明:bisect函数会默认返回右侧的位置索引,同时bisect函数是bisect_right函数的别名。

    场景2:已知一个有序列表,其中列表中有重复元素,查找目标元素的位置索引

    import bisect
    
    # 已知一个有序序列
    ordered_list = [23, 34, 34, 59, 78, 99]
    
    # bisect函数默认返回右侧的位置索引
    des_element = 34
    res = bisect.bisect(ordered_list, des_element)
    print(res)  # res: 3
    
    # bisect函数为bisect_right函数的别名
    des_element = 34
    res = bisect.bisect_right(ordered_list, des_element)
    print(res)  # res: 3
    
    # bisect_left函数默认返回左侧的位置索引
    des_element = 34
    res = bisect.bisect_left(ordered_list, des_element)
    print(res)  # res: 1
    View Code

    说明:如果目标元素会在已知有序列表中多次出现,那么目标元素从已知有序列表的左侧或右侧插入时结果是不同的。

    3. 场景应用

    场景1:替代if-elif语句,例如:判断考生成绩所属的等级问题。

    '''
        考试成绩的档位划分,共分为5个等级:
            1. F等级:[0, 60)
            2. D等级:[60, 70)
            3. C等级:[70, 80)
            4. B等级:[80, 90)
            5. A等级:[90, 100]
    '''
    
    import bisect
    
    
    def get_result(score: (int, float), score_nodes: list = [60, 70, 80, 90], ranks='FDCBA') -> str:
    
        # 校验:分数范围
        if score < 0 or score >100:
            return "score的取值范围:0-100"
    
        # 边界点考虑
        if int(score) == 100:
            return "A"
    
        loc_index = bisect.bisect(score_nodes, score)
        return ranks[loc_index]
    
    print(get_result(50))       # res: F
    print(get_result(60))       # res: D
    print(get_result(85.5))     # res: B
    print(get_result(100))      # res: A
    View Code
  • 相关阅读:
    sublime text添加snippet
    python __globals__, __file__
    Zen of Python
    Python的魔法函数之
    tornado session
    sqlalchemy学习
    自控力
    无需编译、快速生成 Vue 风格的文档网站
    python描述符理解
    python property理解
  • 原文地址:https://www.cnblogs.com/reconova-56/p/13124630.html
Copyright © 2011-2022 走看看