0

I have a list of 25 questions that I'd like to randomly select 7. The list of questions will be in an IRC client (Textual). the following is an example of what I currently have as questions and my proposed process of randomizing 7 from my list.

I'd like to make

questions=[
    'Finish this poem "Roses are red Violets are ..."',
    'What is your favorite food?','Stones or Beatles?',
    'favorite pet?',
    'favorite color?',
    'favorite food?'
]

for q in xrange(3):
    question = ''
    while question not in questions:
        # this is where I'm stuck

I would like something like.

  1. What is your favorite food?
  2. favorite pet?
  3. Stones or Beatles?

The end result will be 7 questions from a pool of 25.

El Gallo
  • 1
  • 3
  • 2
    Possible duplicate of [Python, Generate 'n' unique random numbers within a range](http://stackoverflow.com/questions/22842289/python-generate-n-unique-random-numbers-within-a-range) – AlG Feb 25 '16 at 18:33
  • the difference here is I am generating 7 questions in a random order from a list of questions. – El Gallo Feb 25 '16 at 20:08

3 Answers3

1

You can use shuffle():

from random import shuffle

shuffle(questions)

for question in questions[:7]:
    answer = input(question)
    # do something with answer
pp_
  • 3,435
  • 4
  • 19
  • 27
0

Use random.sample():

import random

for question in random.sample(questions, 7):
    answer = input(question)

You need to have enough questions, however. Right now you have only six questions in the list, so random.sample() won't be able to come up with seven random questions. I'm assuming that your real list has 25 questions since you said from a pool of 25, so I merely comment.

zondo
  • 19,901
  • 8
  • 44
  • 83
  • Review your answer. You must be more specific about the use of [`random.sample`](https://docs.python.org/2/library/random.html#random.sample) – Mauro Baraldi Feb 25 '16 at 18:40
  • I would be happy to fix it if I see something wrong, but so far I don't see what's wrong with it. Enlighten me, please. – zondo Feb 25 '16 at 18:41
  • Using exactly that way the answer, will provide an error, because `questions` list doesn't have to length enough to choice 7 items – Mauro Baraldi Feb 25 '16 at 18:48
0

A good approach could be use random.sample.

>>> from random import sample
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
>>> selected = []

>>> for item in sample(items, 7):
...    selected.append(item)
>>> print selected
['h', 'l', 'j', 'm', 'i', 'e', 'c']
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43