Most elegant way to generate 3-char sequence

Rob Cowie cowie.rob at gmail.com
Fri Jun 9 17:49:44 EDT 2006


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