selecting a random item from a set

Alexander Schmolck a.schmolck at gmx.net
Wed Dec 31 23:37:13 CET 2003


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"))

'as




More information about the Python-list mailing list