[Tutor] Code for python game

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 12 14:17:01 EDT 2016


On 12/10/16 18:40, tracey jones-Francis wrote:

> I want to have a function that will ignore certain words that 
> i have specified in a dictionary.

> the dictionary is called skip_words and has about 20 different strings in.

We shouldn't care inside the function what the external
data is called, we just write it to accept a list of
words (its not a dictionary, it is a list).

> def filter_words(words, skip_words):
>        word = words.strip(skip_words)
>        return word
> 
>>>> filter_words(["help", "me", "please"], ["me", "please"])
>     ['help']

Your code above cannot work because it tries to strip() a list of words.
You can only strip one string at a time, so the first thing you need is
a loop that tests each word.

Secondly strip() removes characters from your string but that's
not necessarily needed here (it depends how you build the input
list...) Let's assume the words are already stripped and in
lowercase.

Now, for each word in your input you want to see if it
is in the skip list. If not add it to your output list - you
haven't got one of those yet so you'll need to create one.

Once you have tested all the input words you can return
the result list. I

It should look something like (untested):

def filter_words(words, skips):
    result = []
    for word in words:
        if word not in skips:
           results.append(word)
    return result

If you know about list comprehensions you can do that
all in one line!


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list