LessonΒ·difficulty 2/5Β·~10 min
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: one built-in throws away duplicates, another turns any collection into an ascending list. Reach for both and feed one into the other β then double-check you're handing back a list, not a set.
Tests
- dedupe + sort
- empty
- all same
- negatives
β¦ Stuck? Ask for a spark
Sign in or create a free account to use your monthly AI explainer allowance.
warming up
Loading editorβ¦
Consolewaiting
$ Console output will appear here.