Generating a random subsequence

Alex Martelli aleax at aleax.it
Mon Jan 7 10:19:39 EST 2002


"Tom Bryan" <tbryan at python.net> wrote in message
news:4jtZ7.4356$Cd6.1933487 at typhoon1.southeast.rr.com...
> I needed to get a random subset of a list, and I was surprised that random
> didn't support it directly.  This function was about the best I could do
> given the time constraints.  I post it so that others can criticize and
> improve it.
>
> def randomSubseq( seq, length ):
>         """getRandomSubSeq( seq, length ) -> subsequence of seq of size
length
>         Generate a (kind of) random subsequence of the specified length
and of the
>         same sequence type as the argument seq."""
>         import random
>         returnSeq = seq[0:0] # get a sequence of the same type as seq

The whole following block:

>         try:
>                 getattr( seq, 'append' )
>                 mutable = 1
>         except AttributeError:
>                 mutable = 0
>         indexes = range( len( seq ) )
>         random.shuffle( indexes )
>         if mutable:
>                 for idx in range(length):
>                         returnSeq.append( seq[indexes[idx]] )
>         else:
>                 for idx in range(length):
>                         returnSeq = returnSeq + seq[indexes[idx]]

can become:
          templist = list(seq)
          random.shuffle(templist)
          for item in templist[:length]:
              returnSeq += item

The += augmented operator dispatches appropriately to in-place or
not-in-place mutation depending on LHO's mutable/immutable nature.

I don't think the possible tiny performance increase in yanking
this determination out of the loop is worth the extra effort and
complication of the above-quoted code.


Alex






More information about the Python-list mailing list