Python Itertools permutations only letters and numbers

后端 未结 6 1089
無奈伤痛
無奈伤痛 2021-01-13 12:42

I need to get only the permutations that have letters and numbers (The permutation can not be. \"A, B, C, D\" I need it like this: \"A, B, C, 1\")

In short, the perm

6条回答
  •  别那么骄傲
    2021-01-13 13:30

    You can generate the proper combinations by combining non-empty combinations from the two sequences.

    import itertools
    
    def combinations(a, b, n):
        for i in xrange(1, n):
            for ca in itertools.combinations(a, i):
                for cb in itertools.combinations(b, n-i):
                    yield ca + cb
    
    for r in combinations(list('abcd'), [1, 2, 3, 4], 4):
        print r
    

    The number of combinations you get is choose(A+B, n) - choose(A, n) - choose(B, n), where A is the number of elements in a, B the number of elements in b, and "choose" is the binomial coefficient.

提交回复
热议问题