forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyarray.py
70 lines (55 loc) · 1.52 KB
/
myarray.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#
# 1) Insertion, deletion and random access of array
# 2) Assumes int for element type
#
# Author: Wenru
#
class MyArray:
"""A simple wrapper around List.
You cannot have -1 in the array.
"""
def __init__(self, capacity: int):
self._data = []
self._capacity = capacity
def __getitem__(self, position: int) -> object:
return self._data[position]
def __setitem__(self, index: int, value: object):
self._data[index] = value
def __len__(self) -> int:
return len(self._data)
def __iter__(self):
for item in self._data:
yield item
def find(self, index: int) -> object:
try:
return self._data[index]
except IndexError:
return None
def delete(self, index: int) -> bool:
try:
self._data.pop(index)
return True
except IndexError:
return False
def insert(self, index: int, value: int) -> bool:
if len(self) >= self._capacity:
return False
else:
return self._data.insert(index, value)
def print_all(self):
for item in self:
print(item)
def test_myarray():
array = MyArray(5)
array.insert(0, 3)
array.insert(0, 4)
array.insert(1, 5)
array.insert(3, 9)
array.insert(3, 10)
assert array.insert(0, 100) is False
assert len(array) == 5
assert array.find(1) == 5
assert array.delete(4) is True
array.print_all()
if __name__ == "__main__":
test_myarray()