Get a random subsequence of elements

Here’s a bit of code to create a sequence of random elements of a desired length, initialized from another sequence.

import random

def random_generator(low, high, count): 
    """Get a generator to return count random numbers between low and high."""
    while count > 0:
        yield random.randint(low, high)
        count -= 1

def random_subsequence(sequence, count, start=0, end=None):
    """Choose count elements from the sequence, optionally restricted between 
    start and end.
    if not end or end > len(sequence) - 1:
        end = len(sequence) - 1

    return (sequence[r] for r in random_generator(start, end, count))

if __name__ == "__main__":
    sequence = [2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29]
    four_primes = random_subsequence(sequence, 4)
    two_big_primes = random_subsequence(sequence, 2, len(sequence)/2)

    print "Four primes:", list(four_primes)
    print "Two big primes:", list(two_big_primes)

Notes: This is similar to the library random.sample() method, except if count is greater than or equal to len(sequence), you can produce “sub” sequences which are longer than the original sequence.

This works equally well with strings or any other subscriptable object (like xrange).



  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: