[Tutor] Random list exercise

Christopher King g.nius.ck at gmail.com
Fri Sep 10 03:59:08 CEST 2010


forgot to send it to the list

On Thu, Sep 9, 2010 at 9:58 PM, Christopher King <g.nius.ck at gmail.com>wrote:

> you could try random.shuffle and save a lot of time, it takes a mutable
> sequence (like a list) and shuffles it
>
>
> On Thu, Sep 9, 2010 at 6:39 PM, lists <lists at justuber.com> wrote:
>
>> >>> Several small and not so small points:
>> >>>
>> >>> 1. you assign wordslen each pass through your loop.  While it doesn't
>> >>> matter in a small loop, it wastes time on the order of the size of
>> your
>> >>> list.  Instead move wordslen = len(...  above your while loop.  Any
>> time you
>> >>> put code in a loop that doesn't change in each iteration, you should
>> move it
>> >>> out of the loop.
>> >>>
>> >>> 2. since you only use chosenword once in your loop, you could remove
>> >>> chosenword = words[index] line and replace chosenword in the
>> append(... with
>> >>> words[index]
>> >>>
>> >>> 3. your list doesn't contain any duplicate words.  Since  your program
>> is
>> >>> supposed to catch this, you should add a duplicate to see if it works.
>> >>> (No!)
>> >>>
>> >>> 4. I think your line del words[index] is supposed to help out with
>> item 3
>> >>> but it doesn't.  It just removes the word you just used selected.
>> >>>
>> >>> 5. And finally, I think you want to print
>> >>>
>> >>> Just minor points.  nice job -- getting there
>> >>> --
>> >>> Joel Goldstick
>>
>> This seems to work Joel,
>>
>> It removes the extraneous assignment of chosenword and gets rid of
>> duplicate entries from the word list.
>>
>> while words: #has entries in it
>>    wordslen = len(words) #get the length of the list
>>    index = random.randint(0, wordslen -1) #get a random index
>>     if words[index] not in randwords: #as long as the word isn't
>> already in the new list
>>        randwords.append(words[index]) #append the random word to a new
>> list
>>         del words[index] #del the word from the old list
>>     else:
>>        del words[index] #remove the duplicate word from the source list
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/a9f5becd/attachment.html>


More information about the Tutor mailing list