mdlong

Unique Character Generator Help

Discussion created by mdlong on Dec 1, 2010
Latest reply on Dec 1, 2010 by mdlong
I am working on a script that will populate 3 letters into a field.  I have to use letters due to field limitations and to make sure that I have enough combinations.  I'm not really sure where I am going wrong but I don't get the repeated values filtered out consistently.  It seems to happen most of the time, just not all.  Any one see anything wrong in my code?

import random, string, arcgisscripting, time

gp = arcgisscripting.create(9.3)
gp.OverwriteOutput = 1

# Lets set up some variables
layer = "Layer Goes Here" 
field = "Code" 
length = 3 # Declares the number of character to be created.

uniquelist = [] # Empty list to store already created characters.


##########Define the random character generator##############

def ranchar(length):
    myrg=random.SystemRandom
    
    characters=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    pw=string.join(myrg(random).sample(characters,length))
    randomval = (pw.replace(' ', '')) # Removes some spaces between the letters.
    
    
    return randomval

#############################################################

cur = gp.UpdateCursor(layer)
row = cur.Next()

while row:
    randomval = ranchar(length) # Grabs a random character.
    
    if randomval in uniquelist: # check to see if it already exists.
        print str(randomval) + " already exists, generating new value"
    else:
        uniquelist.append(randomval) # If the value isn't in the list, adds it.
        print uniquelist[-1] # Just for display.
        row.SetValue(field,uniquelist[-1]) # Grabs the last value from the list and writes it.
    cur.UpdateRow(row)
    row = cur.Next()

# Delete cursor and row objects to remove locks on the data
#
del cur, row
Thanks,

-Mike

Outcomes