To get a sample of 5 elements from an array without replacement in Python, you can use the random.sample()
function from the random
module. The random.sample()
function returns a new list containing unique elements chosen randomly from the input sequence.
Here's an example code snippet that demonstrates how to use random.sample()
to get a sample of 5 elements from an array without replacement:
main.py211 chars10 lines
In this code, we first import the random
module. Then, we define an example array arr
containing 10 numbers. Finally, we use the random.sample()
function to get a sample of 5 elements from arr
without replacement, and store the result in the sample
variable. We then print the sample
variable to see the output.
Note that the random.sample()
function raises a ValueError
if k
is larger than the length of the input sequence. So if you want to get a sample of size k
from an array with n
elements, make sure that k
is less than or equal to n
.
gistlibby LogSnag