Zero-Pad an Image

~8 mincode completion

Implement zero_pad(image, pad) returning the padded 2D array.

Examples

pad=1 around a 2x2 image

Input
zero_pad([[1, 2], [3, 4]], 1)
Output
[[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]

pad=0 is a no-op

Input
zero_pad([[1, 2], [3, 4]], 0)
Output
[[1, 2], [3, 4]]

Hints

Hint 1

Convert the input with before doing elementwise work.

Hint 2

Watch for this: padded only one side.

Requirements

  • image: (H, W) array

  • pad: number of zeros to add on each side

  • Return (H + 2pad, W + 2pad) array

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~8 min

8 employers weight this skill

4 autonomy companies, 1 defense company, 1 health and bio company, 1 enterprise vendor, 1 AI product company. Top match scores 93.

Python
import numpy as np


def zero_pad(image, pad):
    """
    Pad a 2D image with zeros on all four sides.

    Args:
        image: (H, W) array
        pad:   number of zeros to add on each side

    Returns:
        (H + 2*pad, W + 2*pad) array
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.