Data structures and algorithms · Lesson 19 of 60 · Code lesson, JavaScript or Python · Optional
Sets
A set holds values with no duplicates, and adding a value that is already there changes nothing.
Checking whether a value is in a set is fast.
Sets are handy for removing duplicates and for asking whether you have seen something before.
Worked example
In JavaScript, new Set(numbers) removes duplicates, and its size property says how many values remain.
const seen = new Set([1, 2, 2, 3]);
console.log(seen.size);Output: 3
In Python, set(numbers) removes duplicates, and len(...) says how many values remain.
seen = set([1, 2, 2, 3])
print(len(seen))Output: 3
Your turn
The program reads some numbers. Make it print how many different numbers there are, counting each value once.
Your program is checked with these 3 inputs:
Input:
1 2 2 3 3 3
Expected output:
3
Input:
5 5 5
Expected output:
1
Input:
4 8
Expected output:
2
Loading your practice…
Preparing your workspace…