Practice: Unique Words

Practice: Unique Words

This exercise combines lower, split, sets, and one new built-in: sorted takes anything loopable and returns a sorted list — sorted(set(["b", "a"])) is ["a", "b"]. Sorting the set gives the result a predictable order, which a bare set does not have.

Exercise

  1. Define a function named unique_words with one parameter, text.
  2. It returns an alphabetically sorted list of the distinct words in text, lowercased.

unique_words("the cat saw The Dog") returns ["cat", "dog", "saw", "the"].

Run your code to see the output, then press Submit.

Hints

  • Lowercase, split, deduplicate with set, then sorted.
  • The whole body fits in one line, but building it in steps is fine.

Tests

import unittest


class TestUniqueWords(unittest.TestCase):
    def test_mixed_case_duplicates_collapse(self):
        self.assertEqual(
            unique_words("the cat saw The Dog"),
            ["cat", "dog", "saw", "the"],
        )

    def test_empty_text(self):
        self.assertEqual(unique_words(""), [])

    def test_result_is_sorted(self):
        self.assertEqual(unique_words("zebra apple mango"), ["apple", "mango", "zebra"])
def unique_words(text):
    return sorted(set(text.lower().split()))


print(unique_words("the cat saw The Dog"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.