문제

I want to generate the following output:

[11000] all combinations with these numbers, but no doubles

   [11000]
   [01100]
   [00110]
   [00011]
   [10100]
   .
   .
   .

But I cannot figure out how to do that. In my problem the list has 365 values with about 20 ones.

도움이 되었습니까?

해결책 2

You have 365 possible positions to place 20 ones. So one way to approach this is making all 20-length combinations of the 365 positions.

An example of how that could look like in code:

from itertools import combinations

n = 365
r = 20

for indexes in combinations(range(n), r):
    base = [0]*n
    for i in indexes:
        base[i] = 1
    print(base)

Since this is a "n choose r" problem, you'll have lots of possible combinations! To calculate how many, use: n! / (r!(n-r)!) = 365! / (20!(365-20)!) = 426112827338828179808453831565930.

다른 팁

You can use itertools.permutations():

for item in itertools.permutations('11000'):
    print ''.join(item)

You can check that you only get unique strings:

from itertools import filterfalse, permutations # ifilterfalse in 2.x  

def unique_permutations(s):
    seen = set()
    for p in filterfalse(seen.__contains__, permutations(s)):
        seen.add(p)
        yield "".join(p)

I get 10 output values for len(s) == 5:

['11000', '10100', '10010', '10001', '01100', 
 '01010', '01001', '00110', '00101', '00011']

The generator makes it more efficient than building the list up front, and it only joins what it needs to, but you will still be discarding a lot of the permutations.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top