简体   繁体   中英

generating random permutations and combinations (python 3.x)

I have code for calculating the number of combinations or permutations for any given set.

(math.comb(n,k)) and (math.perm(n,k)) so perm = (math.perm(10,5)), perm == 30240 permutations

I would like to generate random permutations and combinations of n and k,
so if n = 10, and k = 5, I would get something like 3,7,1,2,9 as either a perm or comb

What maths function would I use for this?

Edit:
The code should generate an array of k values from a selection of 10 randomly and for the combinations remove each value (k) as it is selected from the main set (n) so there are no repititions of (n). The branch of maths is combinatorics (if that helps)
I am certain there must be a function for this already created.
I have millions of arrays to generate and work through.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM