selecting a random item from a set
Jp Calderone
exarkun at intarweb.us
Tue Dec 30 22:57:18 EST 2003
On Wed, Dec 31, 2003 at 02:40:17AM +0000, Alexander Schmolck wrote:
> "Martin v. Loewis" <martin at v.loewis.de> writes:
>
> > Alexander Schmolck wrote:
> >
> > > Is there a better way? If not, how about something like Set.randompop()?
> >
> > In principle, random.choice "ought to" work.
> > It doesn't, as it expects the set to be indexable.
>
> 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
Alternatively (not as nice, imho):
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
typeOrClass = getattr(seq, '__class__', type(seq))
if hasattr(typeOrClass, '__getitem__'):
return seq[int(self.random() * len(seq))]
else:
# Fallback algorithm
Jp
More information about the Python-list
mailing list