Search code examples
pythonpermutationpython-itertoolsrules

Add rules to permutations using python?


since some days I need to create a long list of random strings of lenght 14 that consist of only letters upper and lowercase, non-repeating, so far so good, I'm simply using itertools permutations and printing to a file

import itertools    

for coma in itertools.permutations(Alphabet, 14):
    s="".join(coma)
    #write to file code

Technical limitations aside (I know this is tons of combinations, space to record them, time it takes, etc, no need to point that out, I know.)

Now I have to add another rule that will help reduce the number of combinations, all strings must have at least 6 uppercase letters and max 8, I have been thinking a lot about how to add this rule because all my ideas require the program to generate the string, check if it meets the criteria, discard if not, but the point is to avoid making combinations that not meet this criteria at all.


Solution

  • You can generate lowercase strings, then pick the number and index of letters to be set to uppercase using the random module:

    import random, string
    for i in range(500):
        number_uppercase = random.randint(6,8)
        idx_uppercase = random.sample(range(14), number_uppercase)
        letter_list = random.sample(string.ascii_lowercase, 14)
        for i in idx_uppercase:
            letter_list[i] = letter_list[i].upper()
        s="".join(letter_list)