You can use the random
module of Python which is preincluded same as math
(so you don't need to install it using pip etc.). First define the set that you want to choose k elements randomly from them, in your example it is the set of integers from 1 to 10, so I use S=[i for i in range(1,11)]
(remember the last element in range is the one before the integer you give it as the termination of the range). Then for receiving k
elements with replacement use choices
command in random
package and for the case without replacement use sample
command. The codes are in below.
import random
S=[i for i in range(1,11)]
A=random.choices(S,k=5)
B=random.sample(S,5)
For example when I ran the above code after asking python to show me S, A and B respectively, I received the following result.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[8, 3, 2, 6, 8]
[3, 9, 6, 1, 10]
You can also use numpy
module to combine the two steps of defining S with a range and then using numpy.random.choice
. But note that, you will have k choices from a the set of 10 integers started from 0 not 1. To choose from a set not defined as n sequel integers starting from 0, you should define it again same as our first method and give it to this command instead of only a number such as 10. To make the choices to be done without replacement, you should add an option replace=False
. See the following code.
import numpy
C=numpy.random.choice(10,5)
D=numpy.random.choice(10,5,replace=False)
S=[i for i in range(1,11)]
A=numpy.random.choice(S,5)
B=numpy.random.choice(S,5,replace=False)
After running this and asking the sets C, D, A and B respectively, I got the followings.
array([5, 5, 1, 4, 7])
array([0, 7, 4, 6, 1])
array([10, 5, 7, 1, 7])
array([6, 5, 7, 8, 1])