Does python have a sorted list?

前端 未结 7 1892
温柔的废话
温柔的废话 2020-11-29 20:16

By which I mean a structure with:

  • O(log n) complexity for x.push() operations
  • O(log n) complexity to find an element
  • O(n) comple
7条回答
  •  一整个雨季
    2020-11-29 20:25

    It may not be hard to implement your own sortlist on Python. Below is a proof of concept:

    import bisect
    
    class sortlist:
        def __init__(self, list):
            self.list = list
            self.sort()
        def sort(self):
            l = []
            for i in range(len(self.list)):
                bisect.insort(l, self.list[i])
            self.list = l
            self.len = i
        def insert(self, value):
            bisect.insort(self.list, value)
            self.len += 1
        def show(self):
            print self.list
        def search(self,value):
            left = bisect.bisect_left(self.list, value)
            if abs(self.list[min([left,self.len-1])] - value) >= abs(self.list[left-1] - value):
                return self.list[left-1]
            else:
                return self.list[left]
    
    list = [101, 3, 10, 14, 23, 86, 44, 45, 45, 50, 66, 95, 17, 77, 79, 84, 85, 91, 73]
    slist = sortlist(list)
    slist.show()
    slist.insert(99)
    slist.show()
    print slist.search(100000000)
    print slist.search(0)
    print slist.search(56.7)
    

    ========= Results ============

    [3, 10, 14, 17, 23, 44, 45, 45, 50, 66, 73, 77, 79, 84, 85, 86, 91, 95, 101]

    [3, 10, 14, 17, 23, 44, 45, 45, 50, 66, 73, 77, 79, 84, 85, 86, 91, 95, 99, 101]

    101

    3

    50

提交回复
热议问题