1
- """
2
- Author : Yashwanth Adimulam
3
- Date : October 22, 2024
4
-
5
- Implement the class of DynamicArray with useful functions based on it.
6
- References: https://en.wikipedia.org/wiki/Dynamic_array
7
- https://www.geeksforgeeks.org/how-do-dynamic-arrays-work/
8
-
9
- """
10
-
11
-
12
1
class DynamicArray :
13
2
def __init__ (self ) -> None :
14
3
self .size = 0 # Number of elements in the array
@@ -28,6 +17,12 @@ def append(self, item: int) -> None:
28
17
>>> arr.append(3)
29
18
>>> arr.array[:arr.size] # Display only the filled part of the array
30
19
[1, 2, 3]
20
+ >>> arr.append(4)
21
+ >>> arr.array[:arr.size]
22
+ [1, 2, 3, 4]
23
+ >>> arr.append(5)
24
+ >>> arr.array[:arr.size]
25
+ [1, 2, 3, 4, 5]
31
26
"""
32
27
if self .size == self .capacity :
33
28
self ._resize (2 * self .capacity ) # Double the capacity
@@ -45,10 +40,11 @@ def _resize(self, new_capacity: int) -> None:
45
40
>>> arr = DynamicArray()
46
41
>>> arr.append(1)
47
42
>>> arr.append(2)
48
- >>> arr.append(3)
49
43
>>> arr._resize(10)
50
44
>>> arr.capacity
51
45
10
46
+ >>> arr.array[:arr.size]
47
+ [1, 2]
52
48
"""
53
49
new_array = [None ] * new_capacity
54
50
for i in range (self .size ):
@@ -74,6 +70,10 @@ def get(self, index: int) -> int:
74
70
Traceback (most recent call last):
75
71
...
76
72
IndexError: index out of range
73
+ >>> arr.get(-1)
74
+ Traceback (most recent call last):
75
+ ...
76
+ IndexError: index out of range
77
77
"""
78
78
if index < 0 or index >= self .size :
79
79
raise IndexError ("index out of range" )
@@ -98,6 +98,9 @@ def __len__(self) -> int:
98
98
>>> arr.append(2)
99
99
>>> len(arr)
100
100
2
101
+ >>> arr.append(3)
102
+ >>> len(arr)
103
+ 3
101
104
"""
102
105
return self .size
103
106
@@ -111,6 +114,9 @@ def __str__(self) -> str:
111
114
>>> arr.append(3)
112
115
>>> str(arr)
113
116
'[1, 2, 3]'
117
+ >>> arr.append(4)
118
+ >>> str(arr)
119
+ '[1, 2, 3, 4]'
114
120
"""
115
121
return "[" + ", " .join (str (self .array [i ]) for i in range (self .size )) + "]"
116
122
0 commit comments