[Tutor] Random module help

Norman Khine norman at khine.net
Sat Oct 6 10:27:50 CEST 2007

Alan Gauld wrote:
> "Norman Khine" <norman at khine.net> wrote
>>>>> a = [q[x] for x in q_keys]
>>>>> a
>> ['1q', '4q', '5q', '7q', '8q']
>>>>> a
>> ['1q', '4q', '5q', '7q', '8q']
>> This only returns the same questions, what am I doing wrong? How do 
>> I
>> return a different set?
> I don't understand your problem.
> You are printing 'a' twice but not doing anything between times.
> So of course it prints the same thing. I'd be worried if it didn't!
> Can you demonstrate what you think is wrong?
> Alan G. 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Sorry, I think I have it ;)


import random
n_questions = 5
q = {1:'1q', 2:'2q', 3:'3q', 4:'4q', 5:'5q', 6:'6q', 7:'7q', 8:'8q', 
9:'9q', 0:'0q'}

if len(q) > n_questions:
    q_keys = random.sample(q.keys(), n_questions)
    q_keys = q.keys()
a = [q[x] for x in q_keys]
print a

So now when I execute python exam.py, I get:
python exam.py

['1q', '2q', '4q', '5q', '6q']
['1q', '4q', '5q', '7q', '8q']
['0q', '2q', '6q', '8q', '9q']
['0q', '1q', '2q', '4q', '9q']

But what I was wondering if possible in achieving is that my questions 
set (q) contains questions that are similar, i.e. they are written in 
different ways, so I wanted to get the random set of unique questions 
rather then have variations of the same question returned in my set.

All the questions are stored in one dictionary, perhaps I need to change 
this structure?

Does it make sense? ;)



More information about the Tutor mailing list