Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Aditya wants a random sample of 5 of the 28 students in his class. He writes random.choices(names, k=5) and gets a list in which one name appears twice. Explain what went wrong. Then give the line that he should have written, and say why a simple random sample must not repeat a member.
In a simple random sample of from , every group of is equally likely, so each member has the chance . Use random.sample (no repeats), never random.choices, and check that the list you choose from covers everyone.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. What went wrong. random.choices picks with replacement. After each pick the name goes back into the list, so it can be picked again.
Step 2. The fix. random.sample(names, 5) picks 5 different names, and every group of 5 is equally likely.
Step 3. Why no repeats. A sample of 5 should hold 5 different people. A repeated name gives one person two votes and leaves a place empty.
Answer: use random.sample(names, 5).
Log in to join the discussion.
Loading…