[Tutor] help with loop that is to be fed out of a word list

John Fouhy john at fouhy.net
Tue Feb 10 05:43:54 CET 2009


2009/2/10 David <ldl08 at gmx.net>:
> Dear list,
>
> out of "Thinking in Python" I take the following code, which
> "takes a word and a string of required letters, and that returns True if
> the word uses all the required letters at least once".
>
>
> def uses_all(word, required):
>    for letter in required:
>        if letter not in word:
>            return False
>    return True
>
> Now, I want to feed this code a list of words. This is what I have so far:
>
>
> def uses_all(required):
>    fin = open('words.txt')
>    for line in fin:
>        word = line.strip()
>        for letter in required:
>            if letter not in word:
>                # print "False!"
>                return False
>        print word

Hi David,

Your first function, top, is pretty good.  Rather than throwing it
away, or changing it, you should seek to use it.

Programming is all about separating tasks.  You've got a function that
answers the question: "Does this word use all the required letters?"

Your next step should be to write another function, which says:

"For each word in the list,
  Does this word use all the required letters?
    If so, print it out."

You can use your first function to make that loop work.

Hope this helps.

-- 
John.


More information about the Tutor mailing list