Am I programming in Python mode?

Justin Sheehy dworkin at ccs.neu.edu
Wed Feb 2 10:47:40 EST 2000


Anders M Eriksson <anders.eriksson at morateknikutveckling.se> writes:

>     if lower:
>         l = ord('a')
>         h = ord('z')
>     else:
>         l = ord('A')
>         h = ord('z')

This is a little redundant.  If you are going to use this approach,
you can put the "h = ord('z')" bit outside the if/else block.

However, I'd recommend doing something a bit different, like using
random.choice() on string.lowercase or string.letters depending on the
value of your 'lower' parameter.

>     str = ""
>     generator = whrandom.whrandom()
>     for i in range (n):
>         ch = generator.randint(l,h)
>         if dublicates:
>             str = str + chr(ch)

Instead of using the + operator over and over again on strings, I'd
put the characters in a list, then join them.  

>             bRepeat = 1
>             while bRepeat:
>                 if not chr(ch) in str:
>                     str = str + chr(ch)
>                     bRepeat = 0
>                 else:
>                     ch = generator.randint(l,h)

I'd be more likely to leave out the bRepeat variable, and do a 
'while 1:' loop, using 'break' where you set bRepeat to 0.

I'd probably do something sort of like this:

import string, random

def randStr(n, lower=1, duplicates=1): 
    if lower: 
        chars = string.lowercase
    else:
        chars = string.letters
    if n > len(chars) and not duplicates: raise "I'd prefer not to infloop"
    char_list = []
    while len(char_list) < n:
        ch = random.choice(chars)
        if duplicates or ch not in char_list:
            print duplicates
            print ch
            print (ch in char_list)
            char_list.append(ch)
    return string.join(char_list, '')

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.

-Justin

 




More information about the Python-list mailing list