All the chances of coming out

Asked 2 years ago, Updated 2 years ago, 15 views

Hello. I want to implement it with Python.

Assume that the array has a length of up to 10, and there are two 0s or 1s in the array. Let's say that there are four 1s and six 0s here, and we want to implement all the arrangements that we can make with this.

ex) [1,1,1,1,0,0,0,0,0,0] [1,1,1,0,1,0,0,0,0,0,] [1,1,1,0,0,1,0,0,0,0] ~~~ [0,0,0,0,0,0,1,1,1,1]

I'd like to ask for your help.

python

2022-09-22 08:23

2 Answers

The default module, itertools, has permutations implemented.

In [1]: import itertools as it

In [2]: L = [1,1,0,0]

In [3]: set(it.permutations(L))
Out[3]:
{(0, 0, 1, 1),
 (0, 1, 0, 1),
 (0, 1, 1, 0),
 (1, 0, 0, 1),
 (1, 0, 1, 0),
 (1, 1, 0, 0)}


2022-09-22 08:23

def comb(m, n, d=0):
    # # print('>'*d, m, n)
    if n == 0:
        return [ [ 0 ] * m ]
    if m == n:
        return [ [ 1 ] * m ]
    r1 = [ l + [ 1 ] for l in comb(m-1, n-1, d+1) ]
    r2 = [ l + [ 0 ] for l in comb(m-1, n, d+1) ]
    return r1+r2

Find a combination that selects 4 digits out of 10 digits.

We implemented it as a recursive function. To see how the recursion goes, you can rotate the print statement at the beginning of the function.


2022-09-22 08:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.