Get a random sample with replacement

PythonPython 3.xRandom

Python Problem Overview


I have this list:

colors = ["R", "G", "B", "Y"]

and I want to get 4 random letters from it, but including repetition.

Running this will only give me 4 unique letters, but never any repeating letters:

print(random.sample(colors,4))

How do I get a list of 4 colors, with repeating letters possible?

Python Solutions


Solution 1 - Python

In Python 3.6, the new random.choices() function will address the problem directly:

>>> from random import choices
>>> colors = ["R", "G", "B", "Y"]
>>> choices(colors, k=4)
['G', 'R', 'G', 'Y']

Solution 2 - Python

With random.choice:

print([random.choice(colors) for _ in colors])

If the number of values you need does not correspond to the number of values in the list, then use range:

print([random.choice(colors) for _ in range(7)])

From Python 3.6 onwards you can also use random.choices (plural) and specify the number of values you need as the k argument.

Solution 3 - Python

Try numpy.random.choice (documentation numpy-v1.13):

import numpy as np
n = 10 #size of the sample you want
print(np.random.choice(colors,n))

Solution 4 - Python

This code will produce the results you require. I have added comments to each line to help you and other users follow the process. Please feel free to ask any questions.

import random

colours = ["R", "G", "B", "Y"]  # The list of colours to choose from
output_Colours = []             # A empty list to append results to
Number_Of_Letters = 4           # Allows the code to easily be updated

for i in range(Number_Of_Letters):  # A loop to repeat the generation of colour
    output_Colours.append(random.sample(colours,1)) # append and generate a colour from the list

print (output_Colours)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkev xlreView Question on Stackoverflow
Solution 1 - PythonRaymond HettingerView Answer on Stackoverflow
Solution 2 - PythontrincotView Answer on Stackoverflow
Solution 3 - PythonPriyankView Answer on Stackoverflow
Solution 4 - PythonCodeCupboardView Answer on Stackoverflow