+ 3
More efficient algorithm
Hi there, I'm working on a project that requires some algorithms in Python with minimal time-consuming nested loops. This is part of my problem and it is called a weighted moving average. There is a full explanation of how to calculate it inside the attached code. I know that the list comprehension method is a great and fast solution, but I want another solution that is more efficient while maintaining the natural sequence of data. Thank you in advance. https://code.sololearn.com/c5GLB6xOM3q1/?ref=app
2 ответов
+ 1
I am working on figuring out what the parameter “period” does. Meanwhile, i think using the sum function or just the whole numpy module would be a possible solution.
0
Here's an alternative approach that doesn't use list comprehensions extensively and aims for efficiency while maintaining the natural sequence of the data:
def wma(data, period):
val = [0] * (period-1)
k = (period * (period + 1)) / 2.0
result = []
total = 0
for i in range(period-1):
total += data[i]
for i in range(len(data)-period+1):
total += data[i + period-1] - data[i-1] if i > 0 else data[i + period-1]
result.append(total / k)
return val + result
print(wma(data, 5))
In this version, we calculate the initial value of `total` as the sum of the first `period-1` elements. Then, as we move the window along the data, we update the total by adding the new element to the current window and subtracting the element that falls out of the window. This approach avoids creating unnecessary lists and should be more memory-efficient compared to using list comprehensions for intermediate calculations.