Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Sets and Uniqueness

~8 mincode completion

A set is a collection with no duplicates and no order:

set([3, 1, 3, 2, 1])     # {1, 2, 3}

That makes de-duplicating a one-liner. Sets are also very fast at answering "is this in here?", much faster than a list once the collection gets large.

seen = {"a", "b"}
"a" in seen        # True
seen.add("c")      # {"a", "b", "c"}
len(seen)          # 3

The catch is that a set has no order. Printing one twice can show the items in different arrangements, so a set is never the right thing to return when order matters. Convert back to a sorted list when you need a stable answer:

sorted(set([3, 1, 3]))    # [1, 3]

Your task:

Write unique_sorted(values) that returns a list of the distinct values, in ascending order.

[3, 1, 3, 2, 1] returns [1, 2, 3].

Example Tests

Duplicates are removed and the rest sorted

Input: {"values":[3,1,3,2,1]}

Expected: [1,2,3]

An already unique list just comes back sorted

Input: {"values":[5,4,6]}

Expected: [4,5,6]

All-identical values collapse to a single item

Input: {"values":[7,7,7]}

Expected: [7]

Python
def unique_sorted(values):
    """
    Remove duplicates and sort what is left.

    Args:
        values: a list

    Returns:
        A sorted list of the distinct values.
    """
    # YOUR CODE HERE
    pass

Run your code to see results

⌘↵ runs against the visible tests

Loading docs…