selecting a random item from a set

Jp Calderone exarkun at intarweb.us
Thu Jan 1 01:16:33 EST 2004


On Wed, Dec 31, 2003 at 10:37:13PM +0000, Alexander Schmolck wrote:
> Jp Calderone <exarkun at intarweb.us> writes:
> > > > Alexander Schmolck wrote:
> > > Maybe not insensibly -- the fairly generic approach outlined above that will
> > > work for any iterable with len is clearly not desirable as default (because of
> > > its time complexity), and just using it as a fallback won't work either,
> > > because AFACT there is no way for `choice` to find out whether its argument is
> > > a sequence or not.
> > 
> > 
> >     def choice(self, seq):
> >         """Choose a random element from a non-empty sequence."""
> >         try:
> >             return seq[int(self.random() * len(seq))]
> >         except TypeError:
> >             # Fallback algorithm
> 
> choice(dict(1:"gets this", 2:"gets that", "three":"gets the key"))
> 

  This is as broken in the current choice implementation as in the one I
proposed.  I don't think it makes any difference to the question at hand.

  Jp




More information about the Python-list mailing list