[Tutor] Random module help

Norman Khine norman at khine.net
Sat Oct 6 14:30:20 CEST 2007


Hi Alan,
Thanks for the suggestion, but I am not sure it is what I am after. From 
your dictionary, for example, I wanted to have a list as:

"what is your name?"
"where do you live?"

then the next time I run the program I will get:

"who are you?
"what is your address?

etc...

rather then, what I have now is:

"what is your name?"
"who are you?"
...

I have updated the code as you suggested to:

import random
n_questions = 5
q = {'1': ['1a', '1b', '1c'],
      '2': ['2a', '2b', '2c'],
      '3': ['3a', '3b', '3c'],
      '4': ['4a', '4b', '4c'],
      '5': ['5a', '5b', '5c'],
      '6': ['6a', '6b', '6c'],
      '7': ['7a', '7b', '7c'],
      '8': ['8a', '8b', '8c']
     }

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

which returns:

[['2a', '2b', '2c'], ['4a', '4b', '4c'], ['5a', '5b', '5c'], ['7a', 
'7b', '7c'], ['8a', '8b', '8c']]

etc...

So from this how do I choose a random element and produce a new 
dictionary like for example:

[2a, 4b, 5c,  7b, 8c]

Thanks



Alan Gauld wrote:
> "Norman Khine" <norman at khine.net> wrote
> 
>> 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.
> 
> It sounds like maybe you need a list of questions against the keys.
> That way you can select one of the list of similar questons at
> random whenever that key is chosen.
> 
> {'q1': ['What is you name?', 'who are you?', 'what are you called?'],
>  'q2': ["What's your address?", 'Where do you live?'],
>  q3: [ etc....]
> }
> 
> HTH,
> 
> 

-- 
Norman



More information about the Tutor mailing list