I am getting an error while finding the moving_average_of_peaks - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: News and Discussions (https://python-forum.io/forum-31.html) +--- Thread: I am getting an error while finding the moving_average_of_peaks (/thread-41398.html) |
I am getting an error while finding the moving_average_of_peaks - sayedsadat - Jan-08-2024 Hello Guys! firstly I would like to say happy new year to all of you, secondly, its a few days which the following code makes me busy, which is mostly correct, there is something which I did wrote wrong, in which I do not get the desired answer: def moving_average_of_peaks(data, n, w): peaks = [] for i in range(w, len(data) - w): if data[i] > max(data[i-w:i]) and data[i] > max(data[i+1:i+w+1]): peaks.append(data[i]) return [(sum(peaks[i:i+n]) / n) for i in range(len(peaks) - n + 1)] if len(peaks) >= n else []I tested 4 cases: moving_average_of_peaks([160, 161, 162, 161, 160, 161, 162, 163, 164, 163, 162], 2,2) - correct:[163.0] moving_average_of_peaks([160, 161, 162, 161, 160, 161, 162, 163, 164, 163, 162], 3,2) - correct:[] moving_average_of_peaks([100, 105, 110, 115, 120, 115, 110, 120, 125, 120, 125, 120, 130, 135, 140, 135, 130], 2,1) - correct:[122.5, 125.0, 132.5] moving_average_of_peaks([100, 105, 110, 115, 120, 115, 110, 120, 125, 120, 125, 120, 130, 135, 140, 135, 130], 2,2) **INCORRECT** got [130.0] but expected [122.5, 132.5] all have correct output, other than the last one, could anyone tell me, what to modify, in order to get a right answer for last one as well, without impacting the rest of test cases negatively. thanks, bests Sayed RE: I am getting an error while finding the moving_average_of_peaks - sgrey - Jan-09-2024 (Jan-08-2024, 11:26 PM)sayedsadat Wrote: Hello Guys! First, wrong subforum. Second, you seem to have an indexing bug in data[i+1:i+w+1] , the i+w+1 can go out of bounds for you because they can become equal to the len(data). If you remove the +1, then the last example returns expected result.
|