snakile
snakile

Reputation: 54521

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?

Upvotes: 11

Views: 2745

Answers (1)

Kabie
Kabie

Reputation: 10673

>>> [''.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']

Upvotes: 38

Related Questions