90. Remove duplicate training texts after normalising them
Duplicate examples leak between train and test and make models memorise. Exact matching misses copies that differ only in case or spacing.
Write dedupe_texts(texts). Normalise each text by lowercasing, stripping, and collapsing every run of whitespace into one space. Keep the first occurrence of each normalised text and return the indices of the kept texts, in order.
def dedupe_texts(texts)Example 1
Input: dedupe_texts(["Hi there", "hi there", "Bye"])
Output: [0, 2]
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Two texts are duplicates when their normalised forms match, so build a normalised key and remember which keys you have already seen.
Hint 2
Loop over texts with their index, normalise each one, and if the key is not in a seen set, add it and record the index.
Hint 3
' '.join(t.lower().split()) lowercases, strips, and collapses every whitespace run in one step; keep indices in a list so the original order is preserved.
Understand the idea
Duplicate training examples make a model memorise and can leak between train and test sets. Exact string matching misses copies that differ only in case or spacing, so first normalise each text, then keep only the first time each normalised form appears. A set of seen keys makes this one fast pass.
texts [' Hello World', 'hello world ', 'HELLO\tworld', 'bye']. Lowercasing, trimming the ends and turning every run of whitespace (spaces, tabs, newlines) into one space gives 'hello world' for the first three and 'bye' for the last. Keep index 0, skip 1 and 2, keep 3. Answer [0, 3].
key = lowercase, strip, then collapse whitespace runs to a single space; if the key is new, record the index and add the key to the set; return the kept indices in order
Lowercasing alone would treat different spacing as different texts. Real pipelines go further with near-duplicate detection, but this exact normalised match is the cheap first step in cleaning pretraining and fine-tuning datasets.