string random generator (Sorry if too stupid, but i am a beginner)

Chris Barker chrishbarker at home.net
Fri Jul 20 23:27:34 CEST 2001


Bjorn Pettersen wrote:
>   import random, string
> 
>   def randomWord(length):
>       res = ''
>       for i in range(length):
>           res += random.choice(string.letters)
>       return res

This will work, if you only want letters, which I think is not the case.
Also, strings are immutable, so the += is creating a new string each
time you add a letter, so it will be a little slow.

The short answer is: chr(), which converts an ascii code to a string
character, so you can what you did above:

import random
def strrnd(n = 24) :
      result = []
      while n :
              n = n - 1
              result.append(chr(random.randrange(1,255,1)))
      return "".join(result)

You can change the range, if you only want letters. Using a list means
that the list is added to rather than re-generated, which I think is
more efficent. The "".join means that you want to join the individual
strings together, putting an empty string between them.

A "for i in range(n):" loop might make more sense, and A niftier (and
probably faster) way to do it is with list comprehensions:

def strrnd(n = 24):
    return "".join([chr(random.randrange(1,255,1)) for x in range(n)])

> > From: Gustavo Vieira Goncalves Coelho Rios 
> > Another problem: This function will be called thousands of 
> > time a minute, so performance is a definitive requirement.

If the strings you are generating are long, performance may be an issue,
in which case, you can check out the Numeric package: 

http://sourceforge.net/projects/numpy

then you could do:

import RandomArray
def strrnd3(n = 24):
    RandomArray.randint(1,255,(n,)).astype('c').tostring() 

RandomArray is a module that provied functions for generating arrays of
random numbers, randint generates an array of random integers,
astype('c') converts the integers to Characters, and tostring() converts
the array to a Python string. Presto.

I did a little time test with various methods. Here it is:

import random, RandomArray

def strrnd0(n = 24):
    res = ''
    for i in range(n):
        res += chr(random.randrange(1,255,1))
    return res

def strrnd1(n = 24):
      result = []
      while n :
              n = n - 1
              result.append(chr(random.randrange(1,255,1)))
      return "".join(result)

def strrnd2(n = 24):
    return "".join([chr(random.randrange(1,255,1)) for x in range(n)])


def strrnd3(n = 24):
    RandomArray.randint(1,255,(n,)).astype('b').tostring() 


# now a time test
import time

start = time.time()

functions = [strrnd0,strrnd1,strrnd2,strrnd3]

N = [5, 25, 100, 1000]
for n in N:
    print "n = %i"% n
    for func, i in zip(functions,range(len(functions))): 
        start = time.time()
        for j in range(1000):
            str = func(n)
        print "The %ith function took %f seconds"%(i,(time.time() -
start))

Running it on my machine I get:
n = 5
The 0th function took 0.340676 seconds
The 1th function took 0.369182 seconds
The 2th function took 0.365142 seconds
The 3th function took 0.375739 seconds
n = 25
The 0th function took 1.570712 seconds
The 1th function took 1.721119 seconds
The 2th function took 1.732749 seconds
The 3th function took 0.403911 seconds
n = 100
The 0th function took 6.188933 seconds
The 1th function took 6.752507 seconds
The 2th function took 6.349224 seconds
The 3th function took 0.579671 seconds
n = 1000
The 0th function took 64.490783 seconds
The 1th function took 66.025794 seconds
The 2th function took 63.856450 seconds
The 3th function took 1.352100 seconds

So:

1) using  strings is in fact a little bit faster than using a list (but
only a tiny bit), this surprised me.

2) using list comprehensions is no faster than looping, in this case.

3) Numeric is about the same for very short strings, and MUCH faster for
long strings.

Numeric is a wonderful package...oh when will it be included in the
standard library!

-Chris



-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list