Search code examples
pythonstringpasswordscombinationspython-itertools

Python: Generate String Combinations with set count of type. (String of x length with, x numbers, x uppercase, x lowercase)


Looking for most efficient way to generate string combinations with qualifiers,

A string of length 16, with 2 numbers, 8 lowercase, 6 uppercase, a way to iterate over all combinations.

Perhaps using itertools.filterfalse or itertools.dropwhile?


Solution

  • Here is a possible solution:

    from itertools import combinations_with_replacement, permutations, product
    from string import ascii_digits, ascii_lowercase, ascii_uppercase
    from sympy.utilities.iterables import multiset_permutations
    
    def generator():
        n_gen = combinations_with_replacement(ascii_digits, 2)
        l_gen = combinations_with_replacement(ascii_lowercase, 8)
        u_gen = combinations_with_replacement(ascii_uppercase, 6)
        for numbers, lowercase, uppercase in product(n_gen, l_gen, u_gen):
            for p in multiset_permutations(numbers + lowercase + uppercase):
                yield ''.join(p)
    

    Example (print 100 strings):

    g = generator()
    i = 0
    
    for s in g:
        if i > 100:
            break
        print(s)
        i += 1
    

    Of course you should not print them all, there are too many!! Indeed there are more than 10^26 possible strings! Do NOT create a list with them unless you know what you are doing.