Question
Need some help with python problem Given Codes: class UndefinedSizeArray(Exception): pass class SparseArrayDict: def __init__(self, *args, default=0., size=None): If args are specified, they form the
Need some help with python problem
Given Codes:
class UndefinedSizeArray(Exception): pass
class SparseArrayDict: def __init__(self, *args, default=0., size=None): """If args are specified, they form the initial values for the array. Otherwise, we need to specify a size.""" self.d = {} self.default = default if len(args) > 0: # We build a representation of the arguments, args. self.length = len(args) for i, x in enumerate(args): if x != default: self.d[i] = x if size is not None: self.length = size elif len(args) > 0: self.length = len(args) else: raise UndefinedSizeArray def __repr__(self): """We try to build a nice representation.""" if len(self) = 0 if x == self.default: # We simply remove any exceptions. if i in self.d: del self.d[i] else: self.d[i] = x # Adjusts the length. self.length = max(self.length, i - 1) def __getitem__(self, i): """Implements evaluation of a[i].""" if i >= self.length: raise IndexError() return self.d.get(i, self.default) def __len__(self): """Implements the len() operator.""" return self.length def __iter__(self): # You may think this is a terrible way to iterate. # But in fact, it's quite efficient; there is no # markedly better way. for i in range(len(self)): yield self[i] def storage_len(self): """This returns a measure of the amount of space used for the array.""" return len(self.d)
def __add__(self, other):
# This is just one way to implement add. This implementation uses
# the __len__, __getitem__, and __setitem__ methods above.
r = Array(size=len(self))
for i in range(len(self)):
r[i] = self[i] + other[i]
return r
def __sub__(self, other):
# Just for the sake of variety, we use a different implementation here.
r = []
for i, x in enumerate(self.a):
r.append(x - other[i])
return Array(*r) # *r unpacks the list r into separate arguments
We saw implementations of the __add__ and __sub__ methods for non-sparse arrays during lecture. These methods implemented element- wise addition (+) and subtraction (-) of non-sparse arrays. For instance, if we have a = Array(1, 2, 3, 4) and b = Array(0, 1, 0, 4), then a + b evaluates to [1, 3, 3, 8] and a - b evaluates to [1, 1, 3, 0]. For this exercise, you will implement the analogous __add__ and __sub__ methods for SparseArrayDict. The efficient way to do this is: First, create a new array for the result, with the appropriate default value. For example, if you're adding arrays, the default value of the new array should be the result of adding the default values of the two existing arrays. Then, figure out which elements are different from the default in one or more) of the arrays being combined. Lastly, for these non-default elements, set their value appropriately in the result array. At a minimum, you will need to define functions named sparse_array_dict_add and sparse_array_dict_sub in the below cell. An elegant way of solving this problem consists of factoring out their common code into a third, common method that they both call, since the two methods are so similar. Otherwise, you can implement sparse_array_dict_add first, and once you get it to work, copy and paste it, and make the few changes required to obtain sparse_array_dict_sub. [] ### Exercise: Implement add and sub for 'SparseArrayDict # YOUR CODE HERE raise NotImplementedError() # These lines add the newly-defined functions # to the already defined SparseArrayDict class as methods. SparseArrayDict. __add__ = sparse_array_dict_add SparseArrayDict. __sub__ = sparse_array_dict_sub We saw implementations of the __add__ and __sub__ methods for non-sparse arrays during lecture. These methods implemented element- wise addition (+) and subtraction (-) of non-sparse arrays. For instance, if we have a = Array(1, 2, 3, 4) and b = Array(0, 1, 0, 4), then a + b evaluates to [1, 3, 3, 8] and a - b evaluates to [1, 1, 3, 0]. For this exercise, you will implement the analogous __add__ and __sub__ methods for SparseArrayDict. The efficient way to do this is: First, create a new array for the result, with the appropriate default value. For example, if you're adding arrays, the default value of the new array should be the result of adding the default values of the two existing arrays. Then, figure out which elements are different from the default in one or more) of the arrays being combined. Lastly, for these non-default elements, set their value appropriately in the result array. At a minimum, you will need to define functions named sparse_array_dict_add and sparse_array_dict_sub in the below cell. An elegant way of solving this problem consists of factoring out their common code into a third, common method that they both call, since the two methods are so similar. Otherwise, you can implement sparse_array_dict_add first, and once you get it to work, copy and paste it, and make the few changes required to obtain sparse_array_dict_sub. [] ### Exercise: Implement add and sub for 'SparseArrayDict # YOUR CODE HERE raise NotImplementedError() # These lines add the newly-defined functions # to the already defined SparseArrayDict class as methods. SparseArrayDict. __add__ = sparse_array_dict_add SparseArrayDict. __sub__ = sparse_array_dict_subStep 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