mercredi 6 mai 2015

Fast method to generate random string sequence

I have a function which returns a string of size N containing a random sequence of characters form a small set {A,B,C,D}. I generate this line as:

def gen_line(N):
  tline = ""
  for i in range(N):
    xrand = random.random()
    if( xrand < 0.25 ):
      ch = "A" 
    elif( xrand < 0.50 ):
      ch = "B" 
    elif( xrand < 0.75 ):
      ch = "C" 
    elif( xrand < 1.00 ):
      ch = "D" 
    else:
      print "ERROR: xrand = %f"%( xrand )
    tline = tline+ch
  return tline

but this is, no doubt, a very inefficient way to do things. Is there a better, my pythonic, way to accomplish this?




Aucun commentaire:

Enregistrer un commentaire