The __getitem__ function does not support the use of negative indices, modify th
ID: 3600892 • Letter: T
Question
The __getitem__ function does not support the use of negative indices, modify this function so that it supports the use of negative indices. (Note: an index such as 3 is equivalent to the traditional index n3 for a list of length n)
import ctypes # provides low-level arrays class DynamicArray: """A dynamic array class akin to a simplified Python list." " " def ini t-(self): """Create an empty array."" " self. n=0 self. capacity = 1 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 not 0Explanation / 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.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.