Search code examples
pythonpython-itertools

how to create all possible orders in a specific length from a list of strings


I have a list of strings that need to fit in 6 characters. The strings can be split but the characters in the string can't be randomized. The strings have different lengths (4 and 3 characters)

I tried a few things with itertools and know how to get all possibilities but not how to get only the possibilities with a specific length requirement.

It's ok to omit the first zero from the list entries.

An example of a list:

wordlist = ["0254", "0294", "0284", "0289", "027", "024", "026", "088"]

It would be ok to get combinations like 025427, 254027, 270254, 027254 (0 and 4 of the list) and the obvious 027088, 088027 (4 and 7 of the list) and even 272488 (4, 5 and 7 of the list)

I think the solution lies in itertools in combination with something else.


Solution

  • Just use a standard double loop and check if you need/can remove zeros to get the desired length

    combinations = []
    for i in wordlist:
        for j in wordlist:
            if len(i) == 4 and len(j) == 4:  # remove both zeros
                combinations.append(i[1:] + j[1:]) 
            elif len(i) == 3 and len(j) == 3:
                combinations.append(i + j)  # dont remove any zero
            else:
                combinations.append(i[1:] + j)  # remove first element zero
                combinations.append(i + j[1:])  # remove second element zero
    

    This will give you all possible combinations (including matching elements with themselves)