1
1
"""
2
- A number container system that uses binary search to
3
- delete and insert values into arrays with O(n logn)
2
+ A number container system that uses binary search to
3
+ delete and insert values into arrays with O(n logn)
4
4
write times and O(1) read times.
5
5
6
6
This container system holds integers at indexes.
11
11
12
12
13
13
class NumberContainer :
14
- def __init__ (self ):
14
+ def __init__ (self ) -> None :
15
15
# Holds number as the key and returns list of indexes where the number is
16
16
# The list of indexes is a sorted array in ascending order
17
17
self .numbermap : dict [int , list [int ]] = {}
@@ -42,13 +42,15 @@ def binary_search_delete(self, array: list[int], item: int) -> list[int]:
42
42
low = mid + 1
43
43
else :
44
44
high = mid - 1
45
- raise ValueError ("The item is not in the array, and therefore cannot be deleted" )
45
+ raise ValueError (
46
+ "The item is not in the array, and therefore cannot be deleted"
47
+ )
46
48
47
49
def binary_search_insert (self , array : list [int ], index : int ) -> list [int ]:
48
50
"""
49
51
Inserts the index into the sorted array
50
52
at the correct position
51
-
53
+
52
54
>>> NumberContainer().binary_search_insert([1,2,3], 2)
53
55
[1, 2, 2, 3]
54
56
>>> NumberContainer().binary_search_insert([0,1,3], 2)
@@ -60,7 +62,8 @@ def binary_search_insert(self, array: list[int], index: int) -> list[int]:
60
62
while low <= high :
61
63
mid = (low + high ) // 2
62
64
if array [mid ] == index :
63
- # If the item already exists in the array, insert it after the existing item
65
+ # If the item already exists in the array,
66
+ # insert it after the existing item
64
67
array .insert (mid + 1 , index )
65
68
return array
66
69
elif array [mid ] < index :
@@ -93,7 +96,7 @@ def change(self, index: int, number: int) -> None:
93
96
self .indexmap [index ] = number
94
97
95
98
# Number not seen before or empty so insert number value
96
- if not number in self .numbermap :
99
+ if number not in self .numbermap :
97
100
self .numbermap [number ] = [index ]
98
101
99
102
# Here we need to perform a binary search insertion in order to insert
@@ -121,7 +124,8 @@ def find(self, number: int) -> int:
121
124
"""
122
125
# Simply return the 0th index (smallest) of the indexes found (or -1)
123
126
return self .numbermap .get (number , [- 1 ])[0 ]
124
-
127
+
128
+
125
129
if __name__ == "__main__" :
126
130
import doctest
127
131
0 commit comments