Created
November 11, 2014 18:09
-
-
Save neotrinity/3f598eb7d6e77fe33226 to your computer and use it in GitHub Desktop.
O(1) insert, remove, contains and get_random
This file contains 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
import random | |
class MyDataStructure(object): | |
def __init__(self): | |
self.d = {} # hash table | |
self.li = [] # dynamic resizing array | |
def insert(self, key): | |
if key in self.d: | |
index = self.d[key] | |
self.d[key] = index | |
self.li[index] = key | |
else: | |
self.d[key] = len(self.li) | |
self.li.append(key) | |
def remove(self, key): | |
if key in self.d: | |
index = self.d[key] # get the index for the key | |
last_key = self.li[-1] # the key for the last element in the list | |
self.li[index] = last_key # set it in the index which you want to remove | |
# update the hashtable to reflect this index change | |
old_index = self.d[last_key] | |
self.d[last_key] = index | |
# proceed to delete the entry | |
del self.d[key] | |
self.li.pop() | |
def contains(self, key): | |
return key in self.d | |
def get_random(self): | |
length = len(self.li) | |
key = self.li[random.randrange(length)] | |
return key | |
if __name__ == '__main__': | |
ds = MyDataStructure() | |
ds.insert('Hen') | |
ds.insert('Donkey') | |
ds.insert('Pig') | |
print "Debug 1: ", ds.d, ds.li | |
for _ in range(4): | |
print ds.get_random() | |
ds.remove('Hen') | |
print "Debug 2: ", ds.d, ds.li |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment