Deep learning: A 1D convolution

Slide a kernel along a list of numbers.

What to build

A program that computes a valid 1D convolution (cross-correlation).

Requirements

  • out[i] = Σⱼ x[i + j] · w[j] for every position where the whole kernel fits.
  • Print the outputs separated by spaces, written with Python's g format.

Input

Line 1: the input values. Line 2: the kernel values.

Output

One line.

Constraints

At most 1,000 inputs; the kernel is not longer than the input.

Example

Input:

1 2 3 4 5
1 0 -1

Output:

-2 -2 -2

Why it works

At each position the kernel measures how well the input around that position matches its pattern, so the output highlights where the pattern occurs.

Examples

Example 1 · Input
1 2 3 4 5
1 0 -1
Expected output
-2 -2 -2
Example 2 · Input
0 1 0 0 1
1 1
Expected output
1 1 0 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Output i is the sum of x[i + j] × w[j] over the kernel positions j.

Hint 2

There are len(x) − len(w) + 1 outputs.

Solution

Show one correct solution (try it yourself first)
x = list(map(float, input().split()))
w = list(map(float, input().split()))
out = [sum(x[i + j] * w[j] for j in range(len(w))) for i in range(len(x) - len(w) + 1)]
print(" ".join(f"{v + 0.0:g}" for v in out))

Lesson: Convolutions →