Search code examples
pythonpython-3.xgeneratormoving-average

moving average in python


I've tried to create a generator function which can find simple moving average of the list, but it doesn't work at all. I think the root of the problem might be in finding sum

def gen(lst, n):
    s = 0
    for i, _ in enumerate(lst):
        if lst[i] < n:
            s += lst[n - (n-i)]

my code does nothing when i play it. What should I do?


Solution

  • if lst[i] < n:
    

    You do not define i

    but I guess i is a index of lst so try:

    for i, _ in enumerate(lst):
      if lst[i] < n:
        s += lst[n - (n-i)]
    

    EDIT:

    def gen(lst, n):
        if n > len(lst):
            print("Sorry can't do this")
        try:
            for i, _ in enumerate(lst[:-(n-1)]):
                s = sum(lst[i:i+n])
                yield s/n
        except ZeroDivisionError:
            print("Sorry can't do this")