# [Python-checkins] Add convolve() to the itertools recipes (GH-23928)

rhettinger webhook-mailer at python.org
Fri Dec 25 19:43:27 EST 2020

```https://github.com/python/cpython/commit/77fde8dc16dc808b9f9838af1aa1253e15cab6ad
branch: master
author: Raymond Hettinger <rhettinger at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2020-12-25T16:43:20-08:00
summary:

Add convolve() to the itertools recipes (GH-23928)

files:
M Doc/library/itertools.rst

diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 612a66f25371d..03416a0a7fbcb 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -786,6 +786,18 @@ which incur interpreter overhead.
def dotproduct(vec1, vec2):
return sum(map(operator.mul, vec1, vec2))

+   def convolve(signal, kernel):
+       # See:  https://betterexplained.com/articles/intuitive-convolution/
+       # convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur)
+       # convolve(data, [1, -1]) --> 1st finite difference (1st derivative)
+       # convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)
+       kernel = list(reversed(kernel))
+       n = len(kernel)
+       window = collections.deque( * n, maxlen=n)
+       for x in chain(signal, repeat(0, n-1)):
+           window.append(x)
+           yield sum(map(operator.mul, kernel, window))
+
def flatten(list_of_lists):
"Flatten one level of nesting"
return chain.from_iterable(list_of_lists)

```