How to generate all possible lines in python?

My goal is to be able to generate all possible strings (letters and numbers) of length x and to be able to activate a code block for each of them. (for example, an iterator) The only problem is that those in itertools do not make copies of the letters on the same line. For instance:

I get "ABC" "BAC" "CAB" etc. instead of "AAA".

Any suggestions?

+6
source share
2 answers

Use itertools.product() :

 >>> import itertools >>> map(''.join, itertools.product('ABC', repeat=3)) ['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA', 'CBB', 'CBC', 'CCA', 'CCB', 'CCC'] 

Note that creating a list containing all the combinations is very inefficient for longer strings - iterate over them instead:

 for string in itertools.imap(''.join, itertools.product('ABC', repeat=3)): print string 

To get all characters and numbers, use string.uppercase + string.lowercase + string.digits .

+21
source

Use itertools.product() if you want to repeat letters:

 >>> from itertools import product >>> from string import ascii_uppercase >>> for combo in product(ascii_uppercase, repeat=3): ... print ''.join(combo) ... AAA AAB ... ZZY ZZZ 

itertools.combinations() and itertools.permutations() are not the right tools for your work.

+6
source

Source: https://habr.com/ru/post/944161/


All Articles