11

My goal is to be able to generate all possible strings (Letters and numbers) of length x and be able to activate a block of code for each one. (like an iterator) The only problem is the ones in the itertools don't make copies of the letter in the same string. For example:

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

Any suggestions?

Azd325
  • 5,752
  • 5
  • 34
  • 57
JD3
  • 410
  • 1
  • 5
  • 14

2 Answers2

30

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 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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 2
    Python 3 changed so that the builtin `map` now returns an iterator. The second suggestion of using `itertools.imap` is not necessary unless you're version of python is < 3.0. – ngoue Jan 08 '16 at 16:52
11

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

>>> 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 correct tools for your job.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343