Am I programming in Python mode?

Martin von Loewis loewis at informatik.hu-berlin.de
Wed Feb 2 23:27:41 CET 2000


Justin Sheehy <dworkin at ccs.neu.edu> writes:

> Note the error-checking in there.  If you don't allow duplicates, you
> can't get a string longer than the set of allowed characters.

This gives the starting point to a different approach: If you don't
want duplicates, it is a matter of picking one element after another
from a set, and removing it after it was picked:

import string, random

def randStr(n, lower=1, duplicates=1): 
    if lower: 
        chars = string.lowercase
    else:
        chars = string.letters
    chars = list(chars)
    char_list = [None]*n
    for i in range(0,n):
        ch = random.choice(chars)
        char_list[i] = ch
        if not duplicates:
            chars.remove(ch)
    return string.join(char_list, '')

This also ignores the test for n>len(chars): You'll get an IndexError
if there are no chars left. It is faster if n is close to len(chars),
since it won't retry the same letters over and over again.

Also, since you'll know the length of the resulting string, you can
pre-allocate the list, and only fill the elements.

Regards,
Martin



More information about the Python-list mailing list