200. Python Program to Remove Duplicates from a List and Keep the Order
EasyPhase 1 · Warm-up
Three tools you know do the job here: split(), not in and append().
Overview
Removing repeats from a list is a common interview question. The hard part is to keep the numbers in the order they first appear.
Problem Statement
Jamal writes down the number of each bus that passes on the way to school. Some buses pass more than once.
Read the numbers. Print each number only once, in the order it first appears, as Without repeats: <numbers>. Put one space between the numbers.
Steps
- Read the line and split it into a list of numbers.
- Make an empty list for the result.
- Loop over the numbers. Add a number to the result only if it is not in the result yet.
- Print
Without repeats:and the result, with one space between the numbers.
Examples
Example 1. Input 4 2 4 7 2 gives:
Without repeats: 4 2 7
Why: 4 and 2 come back later, so their second copies are left out. The order stays 4, 2, 7.
Example 2. Input 5 5 5 gives:
Without repeats: 5
Why: all three numbers are the same, so only the first 5 stays.
Input
One line of whole numbers, with one space between them (1 number or more). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: Without repeats:, a space, and the numbers with one space between them. The tests try 6 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.