Most elegant way to generate 3-char sequence

Steve Holden steve at holdenweb.com
Sat Jun 10 08:43:43 EDT 2006


James Stroud wrote:
> 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,
>>
> 
> 
> A touch more efficient:
> 
> import string
> alpha = string.lowercase
> 
> def generator(choices, length):
>    length -= 1
>    for a in choices:
>      if length:
>        for g in generator(choices, length):
>          yield a + g
>      else:
>        yield a
> 
> for a in generator(alpha, 3):
>    print a
> 
Frankly, this doesn't seem more elegant than the original, particularly 
once it uses a single string.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list