zoukankan      html  css  js  c++  java
  • bisect二分查找模块使用

    import bisect
    L = [1, 3, 3, 6, 8, 12, 15]
    x = 5
    x_insert_point = bisect.bisect_left(L, x)# 在L中查找x,x存在时返回x左侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回左侧位置1
    print(x_insert_point)
    x_insert_point = bisect.bisect_right(L, x) # 在L中查找x,x存在时返回x右侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回右侧位置3
    print(x_insert_point)
    x_insort_left = bisect.insort_left(L, x) # 将x插入到列表L中,x存在时插入在左侧
    print(L)
    x_insort_rigth = bisect.insort_right(L, x) # 将x插入到列表L中,x存在时插入在右侧    
    print(L)

    二分法的实现方式
    def binary_search(t,x):
    temp = t;
    temp.sort();
    low = 0;
    mid = 0;
    high = len(temp)-1;
    while low < high:
    mid = (low+high)/2;
    if x<t[mid]:
    high = mid-1;
    elif x>t[mid]:
    low = mid+1;
    else:
    return mid-1; #是否等价与bisect_left;


    可以用于查找:

    有两个文件,每个都有很多行ip地址,求出两个文件中相同的ip地址:

    复制代码
    # coding:utf-8
    import bisect

    with open('test1.txt', 'r') as f1:
    list1 = f1.readlines()
    for i in range(0, len(list1)):
    list1[i] = list1[i].strip(' ')
    with open('test2.txt', 'r') as f2:
    list2 = f2.readlines()
    for i in range(0, len(list2)):
    list2[i] = list2[i].strip(' ')

    list2.sort()
    length_2 = len(list2)
    same_data = []
    for i in list1:
    pos = bisect.bisect_left(list2, i)
    if pos < len(list2) and list2[pos] == i:
    same_data.append(i)
    same_data = list(set(same_data))
    print(same_data)
  • 相关阅读:
    PMP工具与技术篇--4.4.1-1 储备分析
    PMP--4.4 规划成本管理--成本管理计划
    PMP--4.3.4-2 进度基准
    PMP工具与技术篇--4.3.4-1 关键路径分析
    PMP--4.3.4-1 项目进度计划
    pip超时问题解决
    BurpSuite插件_sqlipy
    文件上传漏洞
    SSL安全评估工具
    子域名爆破工具
  • 原文地址:https://www.cnblogs.com/yoyo008/p/9328340.html
Copyright © 2011-2022 走看看