Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > generators/iterators: filtered random choice

Reply
Thread Tools

generators/iterators: filtered random choice

 
 
gry@ll.mit.edu
Guest
Posts: n/a
 
      09-16-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?

 
Reply With Quote
 
 
 
 
Calvin Spealman
Guest
Posts: n/a
 
      09-16-2006
On 15 Sep 2006 19:17:25 -0700, http://www.velocityreviews.com/forums/(E-Mail Removed) <(E-Mail Removed)> 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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Math.random() and Math.round(Math.random()) and Math.floor(Math.random()*2) VK Javascript 15 05-02-2010 03:43 PM
random.random(), random not defined!? globalrev Python 4 04-20-2008 08:12 AM
c++ as choice for long term application choice. miles.jg C++ 16 11-14-2007 03:43 PM
Can Choice components respond to keyboard input like HTML Choice components? Mickey Segal Java 0 02-02-2004 10:59 PM
Choice of DHCP-server? Is the "IOS-one" a good choice? Fred Cisco 1 12-11-2003 06:25 AM



Advertisments