-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertDeleteRandomDuplicates.py
More file actions
69 lines (57 loc) · 1.8 KB
/
Copy pathInsertDeleteRandomDuplicates.py
File metadata and controls
69 lines (57 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import random
from collections import defaultdict
"""
Data structure that supports the following operations in O(1) time:
- Insert
- Delete
- Get random element from list
*Note:
This version handles duplicates as well. Requires a bit of extra overhead
compared to the singular version.
"""
class InsertDeleteRandom:
def __init__(self):
self._list = []
self._map = defaultdict(set)
"""
Insert a given value into the list
:param val: value to insert
:returns: whether the list already contained the element or not
"""
def insert(self, val):
self._map[val].add(len(self._list))
self._list.append(val)
return len(self._map[val]) == 1
"""
Deletes the passed in value from the list.
Shifts array elements to make delete constant and also to maintain the
data structure porperly.
:param val: value to delete
:returns: delete status
"""
def delete(self, val):
if val not in self._map:
return False
end = len(self._list) - 1
if end in self._map[val]:
self._map[val].remove(end)
else:
pos = self._map[val].pop() # grabs a random value from index list
self._list[pos], self._list[-1] = self._list[-1], self._list[pos] # swap with end
element = self._list[pos] # swapped element (originally at end)
# update index list
self._map[element].remove(end)
self._map[element].add(pos)
self._list.pop() # remove element
if not self._map[val]: # delete from map if list does not contain anymore of it
del self._map[val]
return True
"""
Utilizes the random module to return a random element from the list.
An alternative to random.choice would be using random.randint to generate
a random value within the range of the length of the array and returning
the element at that index.
:returns: random element from list
"""
def get_random(self):
return random.choice(self._arr)