Monday, December 19, 2016

Running Average Query (Python)

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import random

random.seed(1)

def moving_window_average(x, n_neighbors=1):
    n=len(x)
    width = n_neighbors*2 + 1
    y=[]
    for i in range(-n_neighbors,n-n_neighbors):
        temp=0
        for k in range(i,i+width):
            if(k<0):
                #print(str(k) + " " + str(x[0]))
                temp=temp+x[0]
            elif(k>n-1):
                #print(str(k) + " " + str(x[n-1]))
                temp=temp+x[n-1]
            else:
                #print(str(k) + " " + str(x[k]))
                temp=temp+x[k]
        #print(round(temp/width,2))
        y.append(round(temp/width,2))
        temp=0
    print(y)

In case you are checking in DataCamp, it will say solution is not correct unless we remove round function call. :)