0

I am trying to write a program that outputs a list of questions for a test. What I am trying to do is to avoid adding duplicates to the list that way when I print the list I only have a certain amount of unique elements.

def pick_questions(input_list, number_of_picks):
    """Picks random elements of an input list given the number of picks"""
    selected_strings = []

    for index in range(0, number_of_picks + 1):
        random_index = randint(0, len(input_list) - 1)

        if input_list[random_index] not in selected_strings:
            selected_strings.append(input_list[random_index])
            random_index = randint(0, len(input_list) - 1)

    return selected_strings
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

3 Answers3

5

You could use random.sample so there wouldn't be need to do any filtering:

>>> import random
>>> random.sample(range(10), 5)
[1, 4, 3, 8, 7]
niemmi
  • 17,113
  • 7
  • 35
  • 42
0

Initiate your list as a set. Set can only contain unique values. After your work is done, change your set back to list.

set = {1, 2, 3}
>>> set
set([1, 2, 3])
>>> set.add(4) # this would add 4 to the set because the set does not have 4
>>> set
set([1, 2, 3, 4])
>>> set.add(4) # this would *not* add 4 to the set because the set already has 4
>>> set
set([1, 2, 3, 4])
>>> list(set)
[1, 2, 3, 4]

please refer to this link for more details.

Cheolho Jeon
  • 359
  • 1
  • 12
  • You will lose any ordering if you store elements this way. – Holloway May 16 '16 at 09:01
  • 1
    as @Holloway said, this would lose ordering. If you have to preserve the ordering please refer to this post. http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order – Cheolho Jeon May 16 '16 at 09:03
0

If, as it seems, you can use the random module, random has a very convenient function for your use case

from random import sample as pick_questions

sample's documentation from yhe ipython prompt

In [4]: sample?
Signature: sample(population, k)
Docstring:
Chooses k unique random elements from a population sequence or set.

Returns a new list containing elements from the population while
leaving the original population unchanged.  The resulting list is
in selection order so that all sub-slices will also be valid random
samples.  This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique.  If the
population contains repeats, then each occurrence is a possible
selection in the sample.

To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population:   sample(range(10000000), 60)
File:      ~/src/miniconda3/lib/python3.5/random.py
Type:      method
gboffi
  • 22,939
  • 8
  • 54
  • 85