How Random

A Python function that returns a random subset of size n from set s.

from random import randint
 
def random_subset( s, n ):
    if len( s ) < n:
        raise ValueError, ( "Subset larger than input set" )
    l = list( s )
    r = set()
    for i in range( n ):
        r.add( l.pop( randint( 0, len( s ) - i - 1 ) ) )
    return r

I’m dealing with fairly small sets, so this may not be the most computationally efficient way to do it.

May 5th, 2009
Tags: ,
Comments are closed.