Skip to content

Instantly share code, notes, and snippets.

@DiegoGallegos4
Last active April 19, 2019 01:49
Show Gist options
  • Save DiegoGallegos4/82a7c609714eb1c9f702e73f4b3f9f8a to your computer and use it in GitHub Desktop.
Save DiegoGallegos4/82a7c609714eb1c9f702e73f4b3f9f8a to your computer and use it in GitHub Desktop.
Dynamic Array (Vector)
import ctypes
class DynamicArray:
def __init__(self):
self.capacity = 1
self.size = 0
self.array = self._make_array(self.capacity)
def append(self, elt):
if self.size == self.capacity:
self._resize(2 * self.capacity)
self.array[self.size] = elt
self.size += 1
def _resize(self, capacity):
new_array = (capacity * ctypes.py_object)()
for k in range(self.size):
new_array[k] = self.array[k]
self.array = new_array
self.capacity = capacity
def _make_array(self, capacity):
return (capacity * ctypes.py_object)()
def __len__(self):
return self.size
def __getitem__(self, index):
if 0 <= index < self.size:
return self.array[index]
raise IndexError("Out of bounds")
def __setitem__(self, index, value):
if not 0 <= index < self.size:
self.array[index] = value
return
raise IndexError("Out of bounds")
arr = DynamicArray()
arr.append(1)
arr.append(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment