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

This commit is contained in:
Miss Islington (bot) 2020-12-25 20:23:35 -08:00 committed by GitHub
parent 486e70c0a5
commit ed48e9e286
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 0 deletions

View File

@ -769,6 +769,18 @@ which incur interpreter overhead.
def dotproduct(vec1, vec2): def dotproduct(vec1, vec2):
return sum(map(operator.mul, 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): def flatten(list_of_lists):
"Flatten one level of nesting" "Flatten one level of nesting"
return chain.from_iterable(list_of_lists) return chain.from_iterable(list_of_lists)