Sequence Padding
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
Input format:
- Line 1: Target length L
- Line 2: Number of sequences N
- Lines 3 to N+2: Space-separated integers for each sequence
Output: The padded/truncated sequences as a list of lists.
Example:
4 3 1 2 3 5 6 7 8 9 1 2 3 4
[[1, 2, 3, 0], [5, 6, 7, 8], [1, 2, 3, 4]]
Target length: 4
- Sequence [1, 2, 3]: length 3 < 4, pad with one 0 => [1, 2, 3, 0]
- Sequence [5, 6, 7, 8, 9]: length 5 > 4, truncate => [5, 6, 7, 8]
- Sequence [1, 2, 3, 4]: length 4 = 4, no change => [1, 2, 3, 4]
Constraints:
- Pad with 0s at the END (post-padding)
- Truncate from the END (keep first L elements)
- L >= 1
- Sequences contain non-negative integers
Background Knowledge
The problem of sequence padding is a fundamental concept in Natural Language Processing (NLP) and sequence processing. In many NLP tasks, such as text classification, language modeling, and machine translation, input sequences (e.g., sentences or documents) have varying lengths. To efficiently process these sequences using neural networks, it's essential to have sequences of the same length. This is where sequence padding comes into play. By padding or truncating sequences to a fixed length, we can ensure that all sequences have the same length, making it easier to batch and process them.
In sequence processing, sequences can be represented as lists or arrays of integers, where each integer corresponds to a specific token or feature. The target length is the desired length of the padded or truncated sequences. The goal is to transform the input sequences to have this target length while preserving the original information as much as possible. This problem requires understanding of basic data structures, such as lists and arrays, and the ability to manipulate them using loops and conditional statements.
The concept of padding and truncation is crucial in sequence processing. Padding involves adding a special token (in this case, 0) to the end of a sequence to make it longer, while truncation involves removing excess elements from a sequence to make it shorter. These operations are essential in preparing input data for machine learning models, especially when working with sequences of varying lengths.
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
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.