Generate list of 3 numbers with a maximum of 2 duplicates

Viewed 344

How can I generate 3 random numbers between 0 and 5 (inclusive) where it can have a maximum of 2 duplicates efficiently

So the lists I can generate can be:

a = [0, 4, 2]
b = [5, 1, 4]
c = [5, 5, 3]
d = [2, 3, 2]

It cannot generate a list like:

a = [4, 4, 4]
4 Answers

I would suggest creating a list with no more than 2 duplicates and sampling it:

import random

numbers = list(range(6)) * 2
print(random.sample(numbers, 3))

Here's a moderately naive way of solving this:

import random
while True:
    rand = [random.randint(0, 5) for x in range(0, 3)]
    if len(set(rand)) > 1:
        break
print rand

We generate a list of three random values between 0 and 5 inclusive, then convert to a set, and if there is more than one unique value in the set we exit the loop.

First create a list with 3 random number, then loop while all 3 of them are the same, changing e.g. the last number.

import random

lst = [random.randint(0, 5) for __ in range(3)]

while lst[0] == lst[1] == lst[2]:
    lst[2] = random.randint(0, 5) 

If you have a predefined list of choices (as in your comment to other question), the idea is the same, only other function (choice() or choices()) for the random selection:

import random

predefined = ["bob", "john", "mike", "sam", "james", "ross"] 

lst = random.choices(predefined, k=3)

while lst[0] == lst[1] == lst[2]:
    lst[2] = random.choice(predefined)

Some outputs (values of lst):

['mike', 'bob', 'mike']
['sam', 'sam', 'ross']
['ross', 'mike', 'james']
['james', 'bob', 'ross']
['james', 'sam', 'mike']
['sam', 'mike', 'james']
['sam', 'john', 'sam']
  1. Set up a list: [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

  2. Shuffle the list.

  3. Take the first three numbers from the shuffled list.

For extra efficiency, you only need to run the first three steps of a Fisher-Yates shuffle at step 2.

Related