generators/iterators: filtered random choice

G

gry

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?
 
C

Calvin Spealman

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top