Question: #!/usr/bin/env python3 import array # provides access to primitive arrays def copy(self): ''' this behaves like a copy constructor that makes a detailed copy of
#!/usr/bin/env python3
import array # provides access to primitive arrays
def copy(self): ''' this behaves like a copy constructor that makes a detailed copy of self
NOTE: the capacity of the copy matches the elements in self unless the bag is empty, in which case it should be at least 1
Postcondition: x.copy() is x returns false type(x.copy()) == type(x) x.copy() == x
internal capacity of copy is just enough to hold self.__used items
Returns: a new DoubleArrayBag object that contains a copy of all the elements in self and its capacity is equal to number of elements in this bag
Raises: MemoryError if dynamic memory allocation fails ''' copyCapacity = self.__used if (copyCapacity < 1): copyCapacity = 1 newBag = DoubleArrayBag(copyCapacity) # STUDENT IMPLEMENTATION GOES HERE # must copy all elements from self.__data into # the newBag and update any attributes to # adhere to the class invariant
return newBag # end copy
def ensureCapacity(self, newCapacity: int): ''' potentially increase capacity of the bag
Precondition: newCapacity must be an integer and > 0
Postcondition: The bag's capacity is at least newCapacity. If the capacity was already at or greater than newCapacity, then the capacity is left unchanged.
Args: newCapacity (int)
Raises: TypeError if newCapacity is not an integer ValueError if newCapacity not > 1 MemoryError if dynamic memory exhausted ''' if not isinstance(newCapacity, int): raise TypeError("newCapacity must be an integer") if not newCapacity >= 1: raise ValueError("newCapacity must be >= 1")
if len(self.__data) < newCapacity: pass # STUDENT WORK GOES HERE # create a new, bigger array with the capacity # newCapacity, copy all the elements from # self.__data into the new array, and then # update the reference self.__data to refer # to the new array # end if # end ensureCapacity
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
