Merge sorted lists in python

前端 未结 9 991
花落未央
花落未央 2020-12-19 00:50

I have a bunch of sorted lists of objects, and a comparison function

class Obj :
    def __init__(p) :
        self.points = p
def cmp(a, b) :
    return a.p         


        
9条回答
  •  情歌与酒
    2020-12-19 01:16

    Below is an example of a function that runs in O(n) comparisons.

    You could make this faster by making a and b iterators and incrementing them.

    I have simply called the function twice to merge 3 lists:

    def zip_sorted(a, b):
        '''
        zips two iterables, assuming they are already sorted
        '''
        i = 0
        j = 0
        result = []
        while i < len(a) and j < len(b):
            if a[i] < b[j]:
                result.append(a[i])
                i += 1
            else:
                result.append(b[j])
                j += 1
        if i < len(a):
            result.extend(a[i:])
        else:
            result.extend(b[j:])
        return result
    
    def genSortedList(num,seed):
        result = [] 
        for i in range(num):
            result.append(i*seed)
        return result
    
    if __name__ == '__main__':
        a = genSortedList(10000,2.0)
        b = genSortedList(6666,3.0)
        c = genSortedList(5000,4.0)
        d = zip_sorted(zip_sorted(a,b),c)
        print d
    

    However, heapq.merge uses a mix of this method and heaping the current elements of all lists, so should perform much better

提交回复
热议问题