Creating dynamic array in class [python] -
i've written own list
class wraps list
-like array type. array has fixed capacity , when array full want capacity double automatically. example, if base capacity 5 when array full , item added, doubles capacity 10 before adding item.
here's code:
from referential_array import build_array class list: def __init__(self,capacity): assert capacity >0, "capacity cannot negative" self.count = 0 self._array = build_array(capacity) self.capacity = capacity def append(self,item): has_space_left = not self.is_full() if has_space_left: self._array[self.count] = item self.count+=1 else: #issue here create_more_space = list.__init__(self,capacity*2) #if list full, capacity *2 self.count+=1 if __name__== "__main__": mylist = list(6) mylist.append(4) mylist.append(7) mylist.append(1) mylist.append(3) mylist.append(2) mylist.append(17) mylist.append(18) mylist.append(20)
below, first specify size 6. go ahead append more 6 items. right, when python sees there no longer space, capacity doubled , hence 18 , 20 can appended well.
i'm getting error saying capacity not defined @ append function. output i'm trying is:
4 7 1 3 2 17 18 20
the error because members of object in python must accessed self
reference:
create_more_space = list.__init__(self, self.capacity * 2)
i'm not sure why you're doing since built-in python list
type has functionality, i'll assume learning. in case, suggest pulling resizing out separate method can called constructor , append
. also, current set lose contents of array when capacity changes (because you'll assigning new array on top of old one). e.g.
new_array = build_array(capacity) new_array[0:len(self._array)] = self._array self._array = new_array
Comments
Post a Comment