Am I programming in Python mode?

Michael Hudson mwh21 at cam.ac.uk
Wed Feb 2 09:48:54 EST 2000


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

> Hello!
> 
> Being new to Python I would like your comments on this function. Is it
> written in Pytnon mode?

Only you can tell if it was written in Python mode ('round here Python
mode usually refers to the emacs major mode for Python). I can try and
help with style, which is what I'm fairly sure you meant.
 
> The function returns a random string, and have 3 params the lenght of
> the string, lowercase/Uppercase and dublicates
> 
> Any comments and/or suggestions are welcome!!
> 
> // Anders
> 
> 
> 
> def randStr(n, lower=1, dublicates=1):
>     # returns a random string with <n> characters
>     # lower         if true only lowercase letters
>     # dublicates    if true then the same letter can be repeated

This bit could (should) be in a docstring, not a comment.

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

Hmm, does this actually work? ASCII goes like:

... STUVWXYZ[\]^_`abcdefghijk ...

so the above will get strings containing [\]^_` characters.

>     str = ""
>     generator = whrandom.whrandom()

Why do you want your on generator?

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

It's probably better to accumulate substrings into a list and use
string.join to stick them together. This is particularly true in the
single character case, 'cause they're cached.

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

You do know about random.choice don't you? It selects a random item
from a sequnce - and strings are sequences.

So if I were doing this I'd do it like this:

import random,string

def randStr(n,lower=1,duplicates=1):
    """ randStr(n:Integer[,lower,duplicates]) -> String

Generate a random string of length n.
If |lower| is true (the default), only lowercase letters will be used.
If |duplicates| is true (the default), the string may contain duplicates. """
    if lower:
        choices = 'abcdefghijklmnopqrstuvwxyz'
    else:
        choices = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    result = []
    if not duplicates and n > len(choices):
        raise ValueError, "n too large"
    for i in range(n):
        while 1:
            ch = random.choice(choices)
            if duplicates or ch not in result:
                result.append( ch )
                break
    return string.join(result,'')

This probably isn't perfect, but I hope in helps.

Cheers,
Michael



More information about the Python-list mailing list