Skip to content

Instantly share code, notes, and snippets.

@stevieoj
Created May 26, 2017 09:47
Show Gist options
  • Save stevieoj/33187f0e893016ea1ecb14d9c254229a to your computer and use it in GitHub Desktop.
Save stevieoj/33187f0e893016ea1ecb14d9c254229a to your computer and use it in GitHub Desktop.
import ctypes
# Dynamic Array
class DynamicArrays(object):
def __init__(self):
self.n = 0
self.capacity = 1
self.A = self.make_array(self.capacity)
def __len__(self):
return self.n
def __getitem__(self):
if not 0 <= k < self.n:
return IndexError('k is out of bounds')
return self.A[k]
def append(self, elem):
if self.n == self.capacity:
self._resize(2*self.capacity) # 2x if capacity isn't enough
self.A[self.n] = elem
self.n += 1
def _resize(self, capacity):
B = self.make_array(capacity)
for i in range(self.n):
B[i] = self.A[i]
self.A = B
self.capacity = capacity
def make_array(self, capacity):
return (capacity*ctypes.py_object)()
arr = DynamicArrays()
arr.append(20)
arr.append(30)
len(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment