v9.1.1
Menu

Sequence Padding

easyPROSequence ProcessingNLP 2: Applications

Pad or truncate a batch of integer sequences to a fixed length.

Given a list of sequences (lists of integers) and a target length:

  • If a sequence is shorter than the target, pad it with 0s at the end
  • If a sequence is longer than the target, truncate it to the target length
  • If a sequence is exactly the target length, leave it unchanged

Function: pad_sequences(sequences, target_len)

  • sequences: a list of N integer lists (they may have different lengths)
  • target_len: the target length L

Output: The padded/truncated sequences as a list of lists, in the same order as the input.

Example

Input
4
3
1 2 3
5 6 7 8 9
1 2 3 4
Output
[[1, 2, 3, 0], [5, 6, 7, 8], [1, 2, 3, 4]]
Reasoning
  • Inputs: sequences is a batch of three integer lists with lengths 33, 55 and 44; target_len is L=4L = 4, the length every row must end up with.
  • The row [1,2,3][1, 2, 3] has length 3<43 < 4, so it is 4−3=14 - 3 = 1 element short. One 00 goes on the end, giving [1, 2, 3, 0].
  • The row [5,6,7,8,9][5, 6, 7, 8, 9] has length 5>45 > 4, one element too many. Keeping the first 44 elements and dropping the trailing 9 gives [5, 6, 7, 8].
  • [1, 2, 3, 4] already has length exactly 44, so it passes through unchanged.
  • Output: a list of 33 lists, each of length 44, so the batch now forms a regular 3×43 \times 4 grid. Notice the original values always keep their positions at the front; padding and truncation only ever touch the end of a row, and the number of zeros added to a row is max⁡(0,L−n)\max(0, L - n) for a row of length nn.

Constraints

  • Pad with 0s at the END (post-padding)
  • Truncate from the END (keep first L elements)
  • L >= 1
  • Sequences contain non-negative integers

More from NLP 2: Applications

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.