]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Add convolve() to the itertools recipes (GH-23928) (GH-23949)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sat, 26 Dec 2020 04:23:35 +0000 (20:23 -0800)
committerGitHub <noreply@github.com>
Sat, 26 Dec 2020 04:23:35 +0000 (20:23 -0800)
Doc/library/itertools.rst

index 85f4928ce84fbef85378176a4d4774ccb71e6c74..ff5b60d70ff4ede864512a2cb916cea348bef1ef 100644 (file)
@@ -769,6 +769,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([0] * 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)