Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: insert into list faster than O(N)?

I have a sorted list L and I have a binary search for determining where in the list to insert an element such that the resulting list will still be in order.

However L.insert(index,object) needs O(N) time complexity.

Is there another data structure for L that will serve the same purpose, but allows for a faster insertion?

like image 691
user4967499 Avatar asked Jun 05 '15 01:06

user4967499


2 Answers

Check out the blist module.

https://pypi.python.org/pypi/blist/

It claims O(log n) insertion.

usage:

x = #list contents
y = blist(x)
y.insert(index, object) #now works in O(log n)
like image 169
SexmanTaco Avatar answered Sep 27 '22 21:09

SexmanTaco


A shout out to sortedcontainers.SortedList. This will keep your list in order automatically, with a fast insert time.

from sortedcontainers import SortedList

mylist = SortedList([1, 2, 4, 5])
mylist.add(3)
mylist
#>>> SortedList([1, 2, 3, 4, 5], load=1000)

SortedList insertions are amortized O(sqrt n), or O(cbrt n) with different choices of parameters, but it scales better than blist, which is O(log n), because the constants are much better. There is a very in-depth look at performance on their website.

Alternatively, you might be wanting a priority queue in which case you can get potentially-faster inserts with the heapq module.

like image 34
Veedrac Avatar answered Sep 27 '22 22:09

Veedrac