OK, here's a cleanup:
class Simplemovingaverage():
def __init__(self, navg, items):
self.navg = navg
self.items = items
def calculate(self):
av = []
for i in range(len(self.items)):
if i+1 < self.navg:
av.append(0)
else:
av.append(sum(self.items[i+1-self.navg:i+1])/self.navg)
return av
First, you need to use i+1
everywhere, since range
gives 0...navg-1
rather than 1...navg
(you could also do range(1, n+1)
).
Second, you don't need to special-case i+1==self.navg
(:m
is the same as 0:m
).
Third, it makes more sense to return a list rather than printing the results (although I like the other respondent's idea of using yield
to make this a generator!)
Fourth, there's no real reason to hide the number and the list, so I've removed the underscores (python isn't java or c++!).
Finally, this is more general than a "list of prices" averaged over a certain number of "days", so I've renamed the parameters for more generality.