-
Notifications
You must be signed in to change notification settings - Fork 0
/
137.py
56 lines (42 loc) · 1.23 KB
/
137.py
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
"""
Problem:
Implement a bit array.
A bit array is a space efficient array that holds a value of 1 or 0 at each index.
init(size): initialize the array with size
set(i, val): updates index at i with val where val is either 1 or 0.
get(i): gets the value at index i.
"""
class Bit_Array:
def __init__(self, length: int) -> None:
self.length = length
self.indices = set()
def set(self, pos: int, val: int) -> None:
if pos >= self.length:
raise IndexError("Index is out of range")
if val == 0:
if pos in self.indices:
self.indices.remove(pos)
else:
self.indices.add(pos)
def get(self, pos: int) -> int:
if pos >= self.length:
raise IndexError("Index is out of range")
if pos in self.indices:
return 1
return 0
def __repr__(self) -> str:
res = []
for pos in range(self.length):
if pos in self.indices:
res.append(1)
else:
res.append(0)
return str(res)
if __name__ == "__main__":
arr = Bit_Array(8)
print(arr)
arr.set(5, 1)
arr.set(1, 1)
print(arr)
print(arr.get(1))
print(arr.get(4))