Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a random sample with replacement

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?

like image 773
kev xlre Avatar asked Apr 07 '17 15:04

kev xlre


People also ask

Can random sampling be done with replacement?

Sampling is called with replacement when a unit selected at random from the population is returned to the population and then a second element is selected at random. Whenever a unit is selected, the population contains all the same units, so a unit may be selected more than once.

What is simple random sampling with replacement?

Simple random sampling with replacement (SRSWR): SRSWR is a method of selection of n units out of the N units one by one such that at each stage of. selection, each unit has an equal chance of being selected, i.e., 1/ .N.

What does it mean to sample with replacement?

When a sampling unit is drawn from a finite population and is returned to that population, after its characteristic(s) have been recorded, before the next unit is drawn, the sampling is said to be “with replacement”.

Should you sample with replacement?

When we sample with replacement, the two sample values are independent. Practically, this means that what we get on the first one doesn't affect what we get on the second. Mathematically, this means that the covariance between the two is zero. In sampling without replacement, the two sample values aren't independent.


1 Answers

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'] 
like image 113
Raymond Hettinger Avatar answered Sep 17 '22 13:09

Raymond Hettinger