Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate all possible strings in python?

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?

like image 516
JD3 Avatar asked May 02 '13 20:05

JD3


People also ask

How do you print all possible combinations of a string in Python?

To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.

How do you do permutations in python without Itertools?

A. To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.


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

like image 159
ThiefMaster Avatar answered Nov 02 '22 08:11

ThiefMaster


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.

like image 30
Martijn Pieters Avatar answered Nov 02 '22 10:11

Martijn Pieters