easy +8 pts

Convolve 1D signal

Implement 1D discrete convolution with full, same, and valid modes.

Write a function `convolve_1d(signal, kernel, mode='full')` that computes the discrete convolution of two 1D lists of numbers. The kernel is slid across the signal, and at each position we compute the sum of element-wise products (without reversing the kernel, as standard convolution). The function must support three modes: - `'full'` (default): returns the full convolution of length `len(signal) + len(kernel) - 1`. This includes positions where the kernel only partially overlaps the signal; treat out-of-bounds as zero. - `'same'`: returns a result of the same length as the input signal, centered so that the kernel's center aligns with each element of the signal. The center of the kernel is defined as `len(kernel)//2` (integer division). For an even-length kernel, the center is the element at index `len(kernel)//2` (the left of the true center). - `'valid'`: returns only positions where the kernel fully overlaps the signal, i.e., length `len(signal) - len(kernel) + 1` if `len(kernel) <= len(signal)`, otherwise return an empty list. If the mode is not one of the three strings, raise a `ValueError` with message `"Invalid mode"`. Inputs are given as Python lists (or any iterables) of numbers. The function should return a Python list of numbers. If either input is empty, return an empty list. You may not use any external libraries or NumPy. Use plain Python constructs (loops, list comprehensions) — this is about understanding convolution logic.

Constraints

Input lists can be of any length, including 0. Elements are integers or floats. Mode is one of 'full', 'same', 'valid'. Time complexity O(N*M) where N = len(signal) and M = len(kernel). No imports beyond standard library (and none needed).

Example

```python
convolve_1d([1,2,3], [1,1])
# [1, 3, 5, 3]
convolve_1d([1,2,3], [1,1], mode='same')
# [3, 5, 3]
convolve_1d([1,2,3], [1,1], mode='valid')
# [3, 5]
```
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

For 'full', think about padding the signal with zeros on both sides (kernel length - 1 zeros each side) and then sliding the kernel across.
For 'same', you can compute the full convolution and then slice out the correct middle part using `start = len(kernel)//2` and length `len(signal)`.
For 'valid', only compute positions where the kernel completely fits inside the signal.
Handle empty inputs and invalid mode at the beginning.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.