Created
July 7, 2019 01:14
-
-
Save Martlark/9c061e05c523a611482778d7e03b5109 to your computer and use it in GitHub Desktop.
Python SortedList class derived from 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
# sorted list | |
class SortedList(list): | |
def __init__(self, initial_list_values): | |
super().__init__(sorted(initial_list_values)) | |
def append(self, new_value) -> None: | |
for pos, value in enumerate(self): | |
if new_value <= value: | |
super().insert(pos, new_value) | |
break | |
else: | |
super().append(new_value) | |
def extend(self, new_list) -> None: | |
for value in new_list: | |
self.append(value) | |
def insert(self, fake_index, new_value) -> None: | |
self.append(new_value) | |
if __name__ == '__main__': | |
s = SortedList([2, 5, -1, 8]) | |
print(s) | |
s.append(-19) | |
print(s) | |
s.append(999) | |
print(s) | |
s.append(7) | |
print(s) | |
s.insert(3, 4) | |
print(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment