Tuples and setssets-unique-sorted
LessonΒ·difficulty 2/5Β·~10 min
Sets: unique, sorted
Sets: unique, sorted
A set is an unordered collection that automatically throws away duplicates:
python
set([3, 1, 2, 3, 1]) # {1, 2, 3}
len({1, 1, 1}) # 1
That makes "remove duplicates" almost free. Sets have no order, so when you
need a predictable result you hand them to sorted(), which returns a new
list in ascending order.
Your task
Write unique_sorted(values) that returns a list of the distinct numbers
in values, sorted from smallest to largest.
python
unique_sorted([3, 1, 2, 3, 1]) # [1, 2, 3]
unique_sorted([]) # []
unique_sorted([5, 5, 5]) # [5]
Hint: sorted(set(values)) does it in one line β but make sure you return a
list, not a set.
Tests
- dedupe + sort
- empty
- all same
- negatives
- returns a list (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.