11

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?

1 Answer 1

38
>>> [''.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']
3
  • I like this much better than my answer =)
    – Wipqozn
    Feb 28, 2011 at 12:19
  • 13
    Beautiful: instant +1. A slight addition: instead of brackets for list comprehension, using parenthesis will return an interable instead of a full-fledged pregenerated list.
    – salezica
    Feb 28, 2011 at 12:48
  • +1 for solution, and +1 to Santiago for the iterable remark --> laziness is beautiful. Feb 28, 2011 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.