Skip to content

Instantly share code, notes, and snippets.

@Martlark
Created July 7, 2019 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martlark/9c061e05c523a611482778d7e03b5109 to your computer and use it in GitHub Desktop.
Save Martlark/9c061e05c523a611482778d7e03b5109 to your computer and use it in GitHub Desktop.
Python SortedList class derived from List
# 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