Generating a random subsequence

Skip Montanaro skip at pobox.com
Wed Jan 9 10:35:12 EST 2002


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

    Alex> Sorry, a silly error here on my part: sequence addition needs both
    Alex> operands to be of the same type, of course.  So, you need to
    Alex> 'cast' the right-hand side to returnSeq's type, as in the other
    Alex> solution.

I think the better solution is for randomSubseq to return a list and not try
to get cute figuring out the precise sequence type.  The caller will know
the data type returned and easily be able to convert the list back to what
it needs.  Besides, if it wants the return value to be something other than
the input sequence's type, you've wasted effort converting it in the first
place.

    import random
    def randomSubseq(seq, length):
        newseq = list(seq)
        random.shuffle(newseq)
        return newseq[:length]

    print randomSubseq("abcdefghij", 4)
    print "".join(randomSubseq("abcdefghij", 4))
    print tuple(randomSubseq("abcdefghij", 4))

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list