PY-63

Pad ID Sequences and Build a Mask

  • Medium
  • Sequence Arrays
  • Python

Task

Write pad_id_sequences(sequences, target_length, pad_id). sequences is a list of lists of integer IDs. target_length is a non-negative integer.

If any sequence is longer than the target, raise ValueError("sequence exceeds target length"). Otherwise return (ids, mask, lengths). ids is an integer NumPy array of shape (len(sequences), target_length), filled with pad_id after each sequence. mask is a boolean array of the same shape, true only at original ID positions. lengths is a one-dimensional integer array of original lengths. Do not treat an original ID equal to pad_id as padding; position determines validity.

Example

Sequences [[4,0],[7]], target 3, and pad ID 0 produce rows [4,0,0] and [7,0,0], masks [True,True,False] and [True,False,False], and lengths [2,1].

Your implementation

You may import NumPy as np. Do not modify an input, print, or ask for input.