Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. import ctypes
  2. class DynamicArray(object):
  3. #Initialize it
  4. def __init__(self):
  5. #We'll have three attributes
  6. self.n = 0 # by default
  7. self.capacity = 1 # by default
  8. self.A = self.make_array(self.capacity) # make_array will be defined later
  9. #Length method
  10. def __len__(self):
  11. #It will return number of elements in the array
  12. return self.n
  13. def __getitem__(self, k):
  14. #it will return the elements at the index k
  15. if not 0 <=k <self.n:
  16. return IndexError('k is out of bounds')
  17. return self.A[k]
  18. def append(self, element):
  19. #checking the capacity
  20. if self.n == self.capacity:
  21. #double the capacity for the new array i.e
  22. self.resize(2*self.capacity) # _resize is the method that is defined later
  23. # set the n indexes of array A to elements
  24. self.A[self.n] = element
  25. self.n += 1
  26. def _resize(self, new_cap): #new_cap is for new capacity
  27. #declare array B
  28. B = self.make_array(new_cap)
  29. for k in range(self.n):
  30. B[k] = self.A[k] # referencing the elements from array A to B
  31. #ones refered then
  32. self.A = B # A is now the array B
  33. self.capacity = new_cap # resets the capacity
  34. #making the make-array method using ctypes
  35. def make_array(self,new_cap):
  36. return (new_cap * ctypes.py_object)()
  37. arr = DynamicArray()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement