arrays - Arithmetic Progression in Python without storing all the values -
i'm trying represent array of evenly spaced floats, arithmetic progression, starting @ a0 , elements a0, a0 + a1, a0 + 2a1, a0 + 3a1, ... numpy's arange() method does, seems allocate memory whole array object , i'd using iterator class stores a0, a1 , n (the total number of elements, might large). exist in standard python packages? couldn't find so, ploughed ahead with:
class mylist(): def __init__(self, n, a0, a1): self._n = n self._a0 = a0 self._a1 = a1 def __getitem__(self, i): if < 0 or >= self._n: raise indexerror return self._a0 + * self._a1 def __iter__(self): self._i = 0 return self def next(self): if self._i >= self._n: raise stopiteration value = self.__getitem__(self._i) self._i += 1 return value
is sensible approach or revinventing wheel?
well, 1 thing doing wrong should for i, x in enumerate(a): print i, x
.
also, i'd use generator method instead of hassle __iter__
, next()
methods, because solution wouldn't allow iterate on same mylist
twice @ same time 2 different iterators (as self._i
local class).
this better solution gives random access efficient iterator. support in
, len
operators thrown in bonus :)
class mylist(object): def __init__(self, n, a0, a1, eps=1e-8): self._n = n self._a0 = a0 self._a1 = a1 self._eps = eps def __contains__(self, x): y = float(x - self._a0) / self._a1 return 0 <= int(y) < self._n , abs(y - int(y)) < self._eps def __getitem__(self, i): if 0 <= < self._n: return self._a0 + * self._a1 raise indexerror def __iter__(self): current = self._a0 in xrange(self._n): yield current current += self._a1 def __len__(self): return self._n
Comments
Post a Comment