Skip to content

Commit fc55fcd

Browse files
Adding dynamic array implementation
1 parent 917ad62 commit fc55fcd

1 file changed

Lines changed: 114 additions & 0 deletions

File tree

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
"""
2+
Author : Yashwanth Adimulam
3+
Date : October 22, 2024
4+
5+
Implement the class of DynamicArray with useful functions based on it.
6+
7+
"""
8+
9+
10+
class DynamicArray:
11+
def __init__(self) -> None:
12+
self.size = 0 # Number of elements in the array
13+
self.capacity = 1 # Initial capacity of the array
14+
self.array = [None] * self.capacity # Create an array with initial capacity
15+
16+
def append(self, item: int) -> None:
17+
"""
18+
The function adds an item to the end of the dynamic array.
19+
20+
Runtime : O(1) amortized
21+
Space: O(1) amortized
22+
23+
>>> arr = DynamicArray()
24+
>>> arr.append(1)
25+
>>> arr.append(2)
26+
>>> arr.append(3)
27+
>>> arr.array[:arr.size] # Display only the filled part of the array
28+
[1, 2, 3]
29+
"""
30+
if self.size == self.capacity:
31+
self._resize(2 * self.capacity) # Double the capacity
32+
33+
self.array[self.size] = item
34+
self.size += 1
35+
36+
def _resize(self, new_capacity: int) -> None:
37+
"""
38+
Resizes the array to the new capacity.
39+
40+
Runtime : O(n)
41+
Space: O(n)
42+
43+
>>> arr = DynamicArray()
44+
>>> arr.append(1)
45+
>>> arr.append(2)
46+
>>> arr.append(3)
47+
>>> arr._resize(10)
48+
>>> arr.capacity
49+
10
50+
"""
51+
new_array = [None] * new_capacity
52+
for i in range(self.size):
53+
new_array[i] = self.array[i]
54+
self.array = new_array
55+
self.capacity = new_capacity
56+
57+
def get(self, index: int) -> int:
58+
"""
59+
The function returns the item at the specified index.
60+
61+
Runtime : O(1)
62+
Space: O(1)
63+
64+
>>> arr = DynamicArray()
65+
>>> arr.append(1)
66+
>>> arr.append(2)
67+
>>> arr.get(0)
68+
1
69+
>>> arr.get(1)
70+
2
71+
>>> arr.get(2)
72+
Traceback (most recent call last):
73+
...
74+
IndexError: index out of range
75+
"""
76+
if index < 0 or index >= self.size:
77+
raise IndexError("index out of range")
78+
return self.array[index]
79+
80+
def __len__(self) -> int:
81+
"""
82+
Returns the number of elements in the dynamic array.
83+
84+
Runtime : O(1)
85+
Space: O(1)
86+
87+
>>> arr = DynamicArray()
88+
>>> arr.append(1)
89+
>>> len(arr)
90+
1
91+
>>> arr.append(2)
92+
>>> len(arr)
93+
2
94+
"""
95+
return self.size
96+
97+
def __str__(self) -> str:
98+
"""
99+
Returns a string representation of the dynamic array.
100+
101+
>>> arr = DynamicArray()
102+
>>> arr.append(1)
103+
>>> arr.append(2)
104+
>>> arr.append(3)
105+
>>> str(arr)
106+
'[1, 2, 3]'
107+
"""
108+
return "[" + ", ".join(str(self.array[i]) for i in range(self.size)) + "]"
109+
110+
111+
if __name__ == "__main__":
112+
import doctest
113+
114+
doctest.testmod()

0 commit comments

Comments
 (0)