首页 > 编程语言 > 详细

BaezaYates 交集python代码

时间:2017-05-02 09:24:52      阅读:283      评论:0      收藏:0      [点我收藏+]

 

def bsearch(find, arr, low, high):
    while low <= high:
        mid = (low + high) >> 1
        if arr[mid] == find:
            return mid
        elif arr[mid] > find:
            high = mid - 1
        else:
            low = mid + 1
    return -1


def BaezaYates_intersect_helper(A, B, left1, right1, left2, right2, result):
    if left1 > right1 or left2 > right2:
        return
    if right1-left1 > right2-left2:
        left1, left2 = left2, left1
        right1, right2 = right2, right1
        A, B = B, A
    mid = (left1 + right1) >> 1
    index = bsearch(A[mid], B, left2, right2)
    if index >= 0:
        result.append(A[mid])
        BaezaYates_intersect_helper(A, B, left1, mid-1, left2, index-1, result)
        BaezaYates_intersect_helper(A, B, mid+1, right1, index+1, right2, result)
    else:
        if A[mid] > B[right2]:
            BaezaYates_intersect_helper(A, B, left1, mid-1, left2, right2, result)
        elif A[mid] < B[left2]:
            BaezaYates_intersect_helper(A, B, mid+1, right1, left2, right2, result)


def BaezaYates_intersect(A, B):
    result = []
    BaezaYates_intersect_helper(A, B, 0, len(A)-1, 0, len(B)-1, result)
    result.sort()
    return result



from random import randint

if __name__ == "__main__":
    for i in range(2000):
        A = [randint(0, 100) for i in range(30)]
        B = [randint(0, 100) for i in range(30)]

        A.sort()
        B.sort()

        #print A
        #print B

        inter_set = BaezaYates_intersect(A, B)
        #print inter_set

        inter_set2 = set(A) & set(B)

        for data in inter_set:
            assert data in inter_set2
    print "tests passed..."

 

BaezaYates 交集python代码

原文:http://www.cnblogs.com/bonelee/p/6793788.html

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