Generating a large random string

Sean Ross sross at connectmail.carleton.ca
Thu Feb 19 19:10:11 EST 2004


Here's a sample with replacement, where k can be greater than
len(population):

from random import random, seed
from string import letters
from time import clock as now

# derived from random.sample code ... scarcely tested
def sample(population, k):
    """Chooses k random elements from a population sequence. """
    n = len(population)
    result = [None] * k
    for i in xrange(k):
        j = int(random() * n)
        result[i] = population[j]
    return result

n = 1000000
seed(14)
start = now()
s = ''.join(sample(letters, n))
took = now() - start
print "sample with replacement  n: %d took: %2.2fs"%(n, took)

# Output
>>> sample with replacement  n: 1000000 took: 7.68s

Even faster than before, and more correct to boot, heh.






More information about the Python-list mailing list