Combinations of words and digits with specific order

Question:

I need all possible combinations of upper words and digits in this format digit-word-word-word . I tried this code :

upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
all = num + upper_a
def recursive_product(myList, length, myString = ""):
    if length == 0:
       print (myString)
       with open('TDH-H.txt', 'a') as the_file:
           the_file.writelines('{}n'.format('TDH-H' + str(myString)))
       return
    for c in myList:
       recursive_product(myList, length-1, myString + c)

for r in range(4, 5):
    code = recursive_product(all, r)`

But it doesn’t give me the format I want (dwww). What should I do ?

Asked By: Mohammad Jafari

||

Answers:

Try this (assuming you want combinations such as 1ABC):

from itertools import combinations, product
lc = product(num, combinations(upper_a, 3))
for x in lc:
    s = x[0] + ''.join(x[1])
    print(s)
            
Answered By: user19077881

Python offers four different tools in the itertools standard module, depending on what you mean by "combinations":

  • combinations(upper_a, 3) will give all the non repeating combinations: "ABC", "ABD" and so on up to "XYZ"
  • combinations_with_replacement(upper_a, 3) will allow repeating elements in the combinations: so it adds "AAA", "AAB", up to "ZZZ" to the previous result
  • permutations(upper_a, 3) will present the elements of each combination in any possible order: so you won’t have only "ABC" but also "ACB", "BAC", BCA", "CAB", "CBA", and so on
  • product(upper_a, repeat=3) (with the repeat parameter) will give all the permutations with repetitions, like it was a "permutations_with_replacement". This is the only tool that will include your example "8FBB" in its result

Then product (without repeat) will allow you to add the initial digit – see @user answer.

Note, the number of generated values will not be small: 26_000 combinations, 32_760 combos with replace, 156_000 permutations, 175_760 perms with replace

Answered By: gimix