Most elegant way to generate 3-char sequence

akameswaran at gmail.com akameswaran at gmail.com
Sat Jun 10 23:49:04 EDT 2006


I'm not sure if you ever got a good answer.  I for one am too lazy to
look up the pages I found... but - check out
http://aspn.activestate.com/ASPN/search?query=combinations&section=PYTHONCKBK&type=Subsection

Tons of nice recipes... Personally I liked the one that dynamically
generated a nested function - just cuz it was cool - total overkill for
a 3 element permutation.  otherwise a simple nested generator is
perfect for this solution.  Actually you could use the generator
function generator to show you what the generator function should look
like - try sayin that five times fast.
Rob Cowie wrote:
> Hi all,
>
> I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba',
> 'abb', 'abc' etc. all the way to 'zzz'.
>
> How would you construct a generator to acheive this?
>
> A simple, working but somewhat inelegant solution is...
>
> alpha = ['a','b','c','d'] #shortened for brevity
> alpha2 = ['a','b','c','d']
> alpha3 = ['a','b','c','d']
>
> def generator():
>   for char in alpha:
>     for char2 in alpha2:
>       for char3 in alpha3:
>         yield char + char2 + char3
> 
> x = generate()
> x.next() # etc, etc, etc,




More information about the Python-list mailing list