Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in Python which generates all the strings of length n over a given alphabet?

I need a function generateAllStrings(n, alphabet) to do something like this:

generateAllStrings(4, ['a','b'])
>>> ["aaaa", "aaab", "aaba", "aabb", "abaa", .... , "bbba", "bbbb"]

In other words, generateAllStrings(n, alphabet) should return all the possible strings of length n over the chars in the list alphabet.

Is there such a function in itertools or something?

like image 908
snakile Avatar asked Feb 28 '11 12:02

snakile


People also ask

How does LEN () work in Python?

The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.


1 Answers

>>> [''.join(i) for i in itertools.product("ab",repeat=4)]
['aaaa', 'aaab', 'aaba', 'aabb', 'abaa', 'abab', 'abba', 'abbb', 'baaa', 'baab', 'baba', 'babb', 'bbaa', 'bbab', 'bbba', 'bbbb']
like image 137
Kabie Avatar answered Oct 22 '22 17:10

Kabie