About python in the 'bisect management sorted sequence' mind

# With bisect management sorted sequence

bisect (haystack, needle) in search of haystack (hay) in the needle (pointer) the position of the location condition is satisfied, after the needle is inserted into this position, haystack can keep ascending
That is to say in front of the position of this function returns a value equal to or less than the value of the needle, which must be a haystack ordered sequence
It can be used to find the location index bisect, then haystack.insert (index, needle) to insert a new value, which may be used directly
Call bisect library, sys library and random library
import bisect
import sys
import random
num_hay = [1, 4, 5, 6, 8, 10, 19, 23, 23, 35]   # 定义被插入数列
num_need = [0, 1, 2, 5, 8, 10, 14, 20, 23, 38]  # 定义插入数列的数列
row_fmt = '{0:2d} @ {1:2d}    {2}{0:<2d}'   # 定义数据显示格式


def demo(bisect_fn):
    """定义测试bisect的函数"""
    for needle in reversed(num_need):   # reversed() 返回一个反转的迭代器即将数列倒序。只能进行一次循环遍历。显示一次所包含的值!
        position = bisect_fn(num_hay, needle)   # 使用bisect(haystack, needle)函数查询指针位置(第1个数之前为0,第1个数之后为1,第2个数之后为2 )
        offset = position * '  |'   # 通过 pisition 计算制表需要的 “  |” 数
        print(row_fmt.format(needle, position, offset))     # 将数据填入定义好的数据显示格式(row_fmt)中


if __name__ == '__main__':
    if sys.argv[-1] == 'left':   # 执行脚本文件时,python3 脚本文件名 left  即定义数值从位置左侧插入
        bisect_fn_1 = bisect.bisect_left
    else:
        bisect_fn_1 = bisect.bisect     # bisect.bisect 实际上就是bisect.bisect_right 前者是别名
    print('DEMO:', bisect_fn_1.__name__)    # 打印上面判断的函数名
    print('haystack ->', ' '.join('%2d' % n for n in num_hay))      # str.join()通过指定字符连接序列中元素后生成的新字符串。str为指定字符
    demo(bisect_fn_1)   # 调用函数demo

Here Insert Picture Description

A python file used in two ways, the first direct execution as a script, and the second is to import another python script is called (block reuse) performed.
When a .py file is imported as a module, we may not want to be part of the code to run.
So IF name == ' main ': under the code is executed only in the first case (that is directly executed as a script file), and import to other scripts will not be executed.
So if in the case of a defined part of the code need only be used in this script file, it is written in the IF name == ' main ': the next statement.

# Bisect can be used to create a digital index as a look-up table, for example, the scores and achievements correspondence

def grade(score):
    """定义函数grade() 的默认值,score表示要查询的成绩,breakpoints表示成绩划分的界限,grades表示对应输出的成绩等级。"""
    breakpoints = [60, 70, 80, 90]
    grades = 'FDCBA'
    a = bisect.bisect(breakpoints, score)    # 利用bisect()函数来找出在breakpoints中的位置
    return grades[a]    # 然后利用对应返回值,作为索引打印grades中的对应成绩等级


print([grade(score) for score in [33, 58, 67, 85, 97]])

Here Insert Picture Description

# Bisect.insort insert a new element

insort (seq, item) item is inserted into the variable seq in an ordered sequence, and to maintain the ascending order seq.
Call bisect libraries, and random library (top)
random.seed(4)  # random.seed() 表示固定随机生成的数列,不会每次都变。seed()的值任意指定。
my_list = []
for i in range(7):
    new_items = random.randrange(14)
    bisect.insort(my_list, new_items)
    print(str('{:2d} ->'.format(new_items)), my_list)

Here Insert Picture Description
This article is a consolidation of learning notes Source: "smooth python"

Guess you like

Origin blog.csdn.net/Linux_liuge/article/details/94959106