[Edu-sig] source code from SA:10648

Tim Peters tim.peters at gmail.com
Fri Jul 16 04:37:28 CEST 2010


[kirby urner]
...
> Here's the remedied function:
> def askq(quiz = quiz1):
>     score = 0
>     possible = len(quiz)
>     thequiz = quiz[:]  # from hence forth, use thequiz, leave quiz alone
>
>     while len(quiz) > 0:
>         pickone = randint(0, len(quiz)-1)
> ...
>         thequiz.pop(pickone)

You're working too hard ;-)

> Now of course it's problematic to be popping off a list just because
> you wanna not hit the same question twice, and are picking
> questions randomly.  Sure, this is one way to prevent duplicates.
> Even the while loop is pegged to the list length.  Didn't have to
> be this way.
> Just as good if not way better, is to shuffle the indexes ahead
> of time e.g. indexes = range(len(thelist)); indexes.shuffle().
> That'll give you a random sequence on a "primary key" with no
> need to mess with popping data off a list copy.

Still working too hard ;-)

Why not shuffle the quiz guts directly?

def askq(quiz = quiz1):
     thequiz = quiz[:]  # from hence forth, use thequiz, leave quiz alone
     shuffle(thequiz)
     for q, a in thequiz:    # marches over the questions in a random order
         # `q` is the question, `a` is the answer

In fact, if you don't mind permuting the quiz each time, there's no
need to make a copy of the quiz then either (because nothing is ever
removed from it):

def askq(quiz = quiz1):
     shuffle(quiz)
     for q, a in quiz:    # marches over the questions in a random order
         # `q` is the question, `a` is the answer


More information about the Edu-sig mailing list