[Tutor] Help!

wesley chun wescpy at gmail.com
Wed Sep 30 08:03:36 CEST 2009


> I need help writting a program.
> 1) Random string generation
> 2) no repeating letters
> Can anyone help me,please? I am so confused. The only problem is I have to
> use the code that is written there but add on to it.
>
> import random
>
> alphabet = "abcdefghijklmnopqrstuvwxyz"
> myNewString = ""
> for letters in alphabet:
>     myNewString = myNewString + alphabet[random.randrange(26)]
>     print myNewString


hi jessica, and welcome to Python! unfortunately, that's a really ugly
homework problem. it looks like whoever wrote it may be *familiar*
with Python's syntax but isn't experienced enough to develop an
exercise that had a better code example or that made more sense.

have you run the piece of code they gave you and seen what it does? it
does do *some* random string generation but using only lowercase
letters; however, it does not check for repeats. what you need to do
is to take their code and modify it so that it *does* check for
repeats. do you know enough Python to determine whether a particular
letter is contained in a larger string yet? it is the *in* operator,
so try that out.

outside of your homework problem, here are a couple of other problems
i have with this code example, as a matter of best practices:

a. they should be using string.ascii_lowercase instead of making up
something that already exists in the standard library

b. they are using string concatenation of individual letters... i
would use a string join() method call along with a generator
expression

i'm sure others will chime in as well. oh, be sure to post your
modified code along with the entire error stack trace (if any), if you
need some more help. best of luck on your exercise!

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list