generators/iterators: filtered random choice

gry at ll.mit.edu gry at ll.mit.edu
Fri Sep 15 22:17:25 EDT 2006


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?




More information about the Python-list mailing list