Write test code in: if __name__ ==’__main__’: proving that __getitem__ works for
ID: 3605061 • Letter: W
Question
Write test code in: if __name__ ==’__main__’:
proving that __getitem__ works for negative indices
# provides low-level arrays import ctypes from time import time class DynamicArray: """A dynamic array class akin to a simplified Python list.""" def _init (self): "" "Create an empty array.""" self. n 0 self. capacity - self. A = self. make array (self. capacity) #count actual elements # default array capacity # low-level array def len (self) """Return number of elements stored in the array.""" return self. n def getitem (self, k): """Return element at index k.""" if kExplanation / Answer
Here only one def. need to change.
def __getitem__(self, k):
if k < 0:
k = self._n + k // this line will make sure that we pass actual index from beginning for negative index
if not 0 <= k < self.n:
raise IndexError('invalid index')
return self._A[k]
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.