Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created July 1, 2016 09:23
Show Gist options
  • Save limboinf/6922961cbc2eb232bd74f83032fb3947 to your computer and use it in GitHub Desktop.
Save limboinf/6922961cbc2eb232bd74f83032fb3947 to your computer and use it in GitHub Desktop.
python bisect模块构造 有序list操作
# coding=utf-8
"""
python bisect模块构造 有序list操作
:copyright: (c) 2016 by fangpeng(@beginman.cn).
:license: MIT, see LICENSE for more details.
"""
import bisect
class SortedEeception(Exception):
def __init__(self, msg):
self.msg = msg
class SortedList(list):
"""
有序操作
这里插入需要bisect.insort来有序操作
禁用append, extend, 否则整个list就无序了
Usage:
>>>s = SortedList([4, 2, 9, 7]) # [2, 4, 7, 9]
>>>s.insort(3)
>>>s.bisect(6)
"""
def __init__(self, iterable):
super(SortedList, self).__init__(sorted(iterable))
def insort(self, item):
bisect.insort(self, item)
def bisect(self, item):
return bisect.bisect(self, item)
def append(self, p_object):
raise SortedEeception('SortedList not support append')
def extend(self, iterable):
raise SortedEeception('SortedList not support extend')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment