[Tutor] space between words printed

Steven D'Aprano steve at pearwood.info
Sun Nov 3 10:56:11 CET 2013


On Sat, Nov 02, 2013 at 10:18:01PM -0500, Byron Ruffin wrote:
> The output generates a sentence made up of words chosen randomly from
> lists.  I am having trouble getting a space between each of the words.
> Should I be thinking about .split?  Here is the code (ignore indent errors
> as it was copied and pasted) Thank you:
> 
> import random
> 
> def wordList():
> 
>     adj1 = ["Big",        "Small",  "Early",  "Late",    "Red",
> "Tall",    "Short"]
>     subj = ["politician", "man",    "woman",  "whale",   "company",
> "child",   "soldier"]
>     obj =  ["budget",     "money",  "box",    "gift",    "gun",
> "tank",    "drone"]
>     adj2 = ["hot",        "crazy",  "stupid", "fast",    "worthless",
> "awesome", "dirty"]
>     verb = ["spends",     "shoots", "evades", "pursues", "subverts",
> "passes",  "flirts"]
> 
>     y = adj1[generate()], subj[generate()] + obj[generate()] +
> adj2[generate()] + verb[generate()]


Here you choose random words and concatenate them together without any 
space. For example, if you choose "crazy" from adj2 and "flirts" from 
verb, you get "crazyflirts".

Solution #1: try adding a space in between each word, like this:

    adj1[generate()] + " " + subj[generate()] + ... 

That's a bit tedious when you have more than one or two words to add, so 
Python gives you a short cut:

Solution #2: join a list of words, like this:

    # Note the commas not plus signs
    list_of_words = [adj1[generate()], subj[generate()], ... ]
    sentence = " ".join(list_of_words)


By the way, in English you don't normally follow an *adjective* by a 
verb. Adjectives come before nouns: hot coffee, crazy cat, fast car, 
worthless trash, and so forth. It is adverbs that come before verbs: 
quickly run, carefully prepared, slowly drove, and so forth.



There is a problem with your generate function:

> def generate():
>     random0_6 = random.randint(0, 6)
>     return random0_6

This assumes that each word list has exactly 6 words. If it has fewer 
than 6, then sometimes choosing a word will fail. If it has more than 6, 
then words 7, 8, 9, ... will never be choosen.

Instead of using:

    verb[generate()]

to choose a random verb, a better solution is:

    random.choice(verb)


and similarly for nouns, adjectives and so forth:

    list_of_words = [random.choice(adj1), 
                     random.choice(subj),
                     random.choice(obj),
                     ...
                     ]


That will ensure that each word from each word-list is equally likely to 
be chosen.


-- 
Steven


More information about the Tutor mailing list