Created
July 1, 2016 09:23
-
-
Save limboinf/6922961cbc2eb232bd74f83032fb3947 to your computer and use it in GitHub Desktop.
python bisect模块构造 有序list操作
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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