Source code for Exercises.essentials.list_comprehensions.filter_words_list_comp.filter_words

"""
This is the same  exercise as
`Exercises.essentials.basic_loops.filter_words`
with some wrinkles.

We provided you with the following beginning of a famous children song.
You were supposed
to print out only words that start with "o", ignoring case::

    My Bonnie lies over the ocean.
    My Bonnie lies over the sea.
    My Bonnie lies over the ocean.
    Oh bring back my Bonnie to me.

Question 1
----------

What you did in the previous exercise was something like this::

    >>> lyrics = lyrics.replace('.',"")
    >>> lyrics = lyrics.replace(',',"")

    >>> words = lyrics.split()
    >>> o_words = []
    >>> for word in words:
            if word[0] == "o":
               o_words.append(word)

The last step used a basic `for`-loop.
Your task in this exercise is to do the same things
but replace the last step with a **list comprehension**.


Question 2
----------

Bonus: Print out words only once.

.. hint::

   Cast your list to another Python standard datastructure that will enforce uniqueness.

Question 3
----------

If we are always going to collect all the o-words and then
remove duplicates, we could build a set directly rather than going
through a list. Use a set comprehension (or a generator expression if
you are using an older version of Python) to produce the set of words
that start with "ob".
"""

lyrics = """ My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
Oh bring back my Bonnie to me."""

lyrics = lyrics.replace('.',"")
lyrics = lyrics.replace(',',"")


def question_one (lyrics):
    words = lyrics.split()
    # Your code here
    o_words = [] # Your code replaces the "[ ]" here.
    return o_words


def question_two (lyrics):
    # your code goes here
    pass


[docs]def question_three (lyrics): """ Start with lyrics string, make it a list, narrow down to words starting with "o", enforce uniqueness, all in one step. """ # Your code return unique_o_words
if __name__ == '__main__': o_words = get_o_words(lyrics) print("words that start with 'o':") print(o_words) unique_o_words = question_two(lyrics) print(unique_o_words) unique_o_words2 = question_three(lyrics) print(unique_o_words2) # Copyright 2008-2016, Enthought, Inc. # Use only permitted under license. Copying, sharing, redistributing or other unauthorized use strictly prohibited. # http://www.enthought.com