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?
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.
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.
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”.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With