generators/iterators: filtered random choice

Calvin Spealman ironfroggy at gmail.com
Sat Sep 16 01:08:54 EDT 2006


On 15 Sep 2006 19:17:25 -0700, gry at ll.mit.edu <gry at ll.mit.edu> wrote:
> I want a function (or callable something) that returns a random
> word meeting a criterion.  I can do it like:
>
> def random_richer_word(word):
>     '''find a word having a superset of the letters of "word"'''
>     if len(set(word) == 26): raise WordTooRichException, word
>     while True:
>         w = random.choice(words)
>         if set(w) - set(word):  # w has letters not present in word
>             return w
>
> This seems like a perfect application for generators or iterators,
> but I can't quite see how.  Any suggestions?

Simply change the return to yield. The function will return a
generator which will iterate over each new word found. I would fix it
up a bit more than that, however. For example, create the set for
word's letters before the loop, and keep a set of previously yielded
words, so you dont use the same one twice.

Alternatively, maybe you meant that you still want to get a single
word, but you want to iterate until its done, so its non-blocking in
nature. In that case, you might still yield, but add an else block to
yield None, and keep iterating until it yields something evaluating
true. In either case I would be pre-computing that set of subset
letters.



More information about the Python-list mailing list