TensorTonicTensorTonic
Problems
Study PlansProjectsNewInterviewPricingFeedback
Problems
Loading...
1 / 1

Pad Sequences

NLPData Processing
Medium

In NLP, batches often need sequences of equal length. Given a list of token ID sequences (lists of ints), pad them with a special pad_value to match the length of the longest sequence.

Loading visualization...

Examples

Input: seqs = [[1, 2], [3, 4, 5], [6]], pad_value = 0, max_len = None

Output: [[1, 2, 0], [3, 4, 5], [6, 0, 0]]

Explanation: The longest sequence has length 3, so shorter sequences are padded on the right.

Input: seqs = [[1, 2, 3], [4]], pad_value = -1, max_len = None

Output: [[1, 2, 3], [4, -1, -1]]

Hint 1

When max_len is None, derive it from the longest sequence and use zero for an empty collection.

Hint 2

Initialize the output with np.full, then copy each truncated sequence into its row.

Requirements

  • If max_len is None, use the maximum length among sequences
  • If some sequences are shorter, pad them at the end with pad_value
  • If some sequences are longer than max_len, truncate them at the end
  • If seqs is empty, return an array of shape (0, 0)
  • Output must be a NumPy array of dtype int

Constraints

  • Number of sequences N ≤ 10,000
  • Each sequence length ≤ 1,000
  • NumPy required
Try Similar Problems
Text ChunkingRemove StopwordsWord Count DictBatch GeneratorBigram Probabilities

Sign in to take notes on this problem

Case 1
Case 2

Accepts: array

Accepts: number

Accepts: any

You must run your code first.
PrevNext

Pad Sequences

NLPData Processing
Medium

In NLP, batches often need sequences of equal length. Given a list of token ID sequences (lists of ints), pad them with a special pad_value to match the length of the longest sequence.

Loading visualization...

Examples

Input: seqs = [[1, 2], [3, 4, 5], [6]], pad_value = 0, max_len = None

Output: [[1, 2, 0], [3, 4, 5], [6, 0, 0]]

Explanation: The longest sequence has length 3, so shorter sequences are padded on the right.

Input: seqs = [[1, 2, 3], [4]], pad_value = -1, max_len = None

Output: [[1, 2, 3], [4, -1, -1]]

Hint 1

When max_len is None, derive it from the longest sequence and use zero for an empty collection.

Hint 2

Initialize the output with np.full, then copy each truncated sequence into its row.

Requirements

  • If max_len is None, use the maximum length among sequences
  • If some sequences are shorter, pad them at the end with pad_value
  • If some sequences are longer than max_len, truncate them at the end
  • If seqs is empty, return an array of shape (0, 0)
  • Output must be a NumPy array of dtype int

Constraints

  • Number of sequences N ≤ 10,000
  • Each sequence length ≤ 1,000
  • NumPy required
Try Similar Problems
Text ChunkingRemove StopwordsWord Count DictBatch GeneratorBigram Probabilities

Sign in to take notes on this problem

Case 1
Case 2

Accepts: array

Accepts: number

Accepts: any

You must run your code first.