I am extending the functionalities of a Python list and I would like to include a method to normalize a vector to the [0, 1]
range, by using element-wise operations. I came out with this solution, but find that using two classes does not seem clean. The main motivation for using two classes is that the output of data - min(data)
from normalize()
returns a Python list (due to how __sub__()
was implemented), and that native list does not seem to have __truediv__()
implemented.
How can I achieve the normalize()
method and avoid the creation of the intermediate _BaseList
class? The project I am working on has very constrained memory and I cannot use Numpy.
class _BaseList(list): def __init__(self, data): super().__init__(data) def __sub__(self, value): if type(value) in (int, float): return [elem - value for elem in self] elif type(value) is list and len(value) == len(self): return [a - b for a, b in zip(value, self)] def __truediv__(self, value): if type(value) in (int, float): return [elem / value for elem in self] elif type(value) is list and len(value) == len(self): return [a / b for a, b in zip(value, self)] class Array(_BaseList): def __init__(self, data=None): super().__init__(data) def normalize(self): print(type(self)) return _BaseList((self - min(self))) / float(max(self) - min(self))