Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Please help with the following python functions by following the instructions in the skeleton code: from static_array import StaticArray class DynamicArrayException(Exception): DO NOT CHANGE THIS
Please help with the following python functions by following the instructions in the skeleton code:
from static_array import StaticArray class DynamicArrayException(Exception): """DO NOT CHANGE THIS CLASS IN ANY WAY""" pass class DynamicArray: def __init__(self, start_array=None): """ Initialize new dynamic array DO NOT CHANGE THIS METHOD IN ANY WAY """ self._size = 0 self._capacity = 4 self._data = StaticArray(self._capacity) if start_array is not None: for value in start_array: self.append(value) def __str__(self) -> str: """ Return content of dynamic array in human-readable form DO NOT CHANGE """ out = "DYN_ARR Size/Cap: " out += str(self._size) + "/" + str(self._capacity) + ' [' out += ', '.join([str(self._data[_]) for _ in range(self._size)]) return out + ']' def __iter__(self): """ Create iterator for loop """ self._index = 0 return self def __next__(self): """ Obtain next value and advance iterator """ try: value = self[self._index] except DynamicArrayException: raise StopIteration self._index += 1 return value def get_at_index(self, index: int) -> object: """ Return value from given index position Invalid index raises DynamicArrayException """ if index < 0 or index >= self._size: raise DynamicArrayException return self._data[index] def set_at_index(self, index: int, value: object) -> None: """ Store value at given index in the array Invalid index raises DynamicArrayException """ if index < 0 or index >= self._size: raise DynamicArrayException self._data[index] = value def __getitem__(self, index) -> object: """ Same functionality as get_at_index() method above, but called using array[index] syntax """ return self.get_at_index(index) def __setitem__(self, index, value) -> None: """ Same functionality as set_at_index() method above, but called using array[index] syntax """ self.set_at_index(index, value) def is_empty(self) -> bool: """ Return True is array is empty / False otherwise """ return self._size == 0 def length(self) -> int: """ Return number of elements stored in array DO NOT CHANGE THIS METHOD IN ANY WAY """ return self._size def get_capacity(self) -> int: """ Return the capacity of the array DO NOT CHANGE THIS METHOD IN ANY WAY """ return self._capacity def print_da_variables(self) -> None: """ Print information contained in the dynamic array. Used for testing purposes. DO NOT CHANGE THIS METHOD IN ANY WAY """ print(f"Length: {self._size}, Capacity: {self._capacity}, {self._data}") # ----------------------------------------------------------------------- def resize(self, new_capacity: int) -> None: """ This function changes the capacity of the underlying storage of elements in the dynamic array The function should only accept positive integers and cannot be smaller than the number of elements currently stored in the dynamic array """ pass def append(self, value: object) -> None: """ Adds a new value at the end of the dynamic array If the internal storage associated with the dynamic array is full then the capacity needs to be doubled before adding a new value """ pass def insert_at_index(self, index: int, value: object) -> None: """ This function adds a new value at the specified index in the dynamic array Index 0 is the beginning of the array If the provided index is invalid the method raises "DynamicArrayException" If the array contains N elements, valid indices are [0, N] inclusive If internal storage is full then need to double the capacity """ pass
----------------------------------------------------------------------------------------------------------------------------------------------
#static_array.py
class StaticArrayException(Exception): """ Custom exception for Static Array class. Any changes to this class are forbidden. """ pass class StaticArray: """ Implementation of Static Array Data Structure. Implemented methods: get(), set(), length() Any changes to this class are forbidden. """ def __init__(self, size: int = 10) -> None: """ Create array of given size. Initialize all elements with values of None. If requested size is not a positive number, raise StaticArray Exception. """ if size < 1: raise StaticArrayException('Array size must be a positive integer') # The underscore denotes this as a private variable and # private variables should not be accessed directly. # Use the length() method to get the size of a StaticArray. self._size = size # this is a built-in list and is used here self._data = [None] * size def __iter__(self) -> None: """ Disable iterator capability for StaticArray class. This means loops and aggregate functions like those shown below won't work: arr = StaticArray() for value in arr: # will not work min(arr) # will not work max(arr) # will not work sort(arr) # will not work """ return None def __str__(self) -> str: """Override string method to provide more readable output.""" return f"STAT_ARR Size: {self._size} {self._data}" def get(self, index: int): """ Return value from given index position. Invalid index raises StaticArrayException. """ if index < 0 or index >= self.length(): raise StaticArrayException('Index out of bounds') return self._data[index] def set(self, index: int, value) -> None: """ Store value at given index in the array. Invalid index raises StaticArrayException. """ if index < 0 or index >= self.length(): raise StaticArrayException('Index out of bounds') self._data[index] = value def __getitem__(self, index: int): """Enable bracketed indexing.""" return self.get(index) def __setitem__(self, index: int, value: object) -> None: """Enable bracketed indexing.""" self.set(index, value) def length(self) -> int: """Return length of the array (number of elements).""" return self._size if __name__ == "__main__": # Using the Static Array # # Can use either the get/set methods or [] (bracketed indexing) # # Both are public methods; using the [] calls the corresponding get/set # # Create a new StaticArray object - is the default size arr = StaticArray() arr.set(0, 'hello') arr[0] = 'hello' print(arr.get(0)) print(arr[0]) # Print the number of elements stored in the array print(arr.length()) # Create a new StaticArray object to store 5 elements arr = StaticArray(5) # Set the value of each element equal to its index multiplied by 10 for index in range(arr.length()): arr[index] = index * 10 # Print the values of all elements in reverse order for index in range(arr.length() - 1, -1, -1): print(arr[index]) forbidden_list = [None] * 10 print(type(arr)) print(type(forbidden_list))
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started