On 10/06/2006 7:49 AM, 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...
You're not wrong. > > alpha = ['a','b','c','d'] #shortened for brevity Hope you remember the alphabet correctly. Why type all that punctuation? Any reason this cruft is global (i.e. not local to the generator)? > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] Hope you get the redundant copy/paste right. > > def generator(): > for char in alpha: Why stop at two spaces? One-space indentation is syntactically correct :-) > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 > > x = generate() Did you meant "generator"? > x.next() # etc, etc, etc, > |>> def generator(): ... import string ... alpha = string.ascii_lowercase ... for char in alpha: ... for char2 in alpha: ... for char3 in alpha: ... yield char + char2 + char3 ... |>> x = generator() |>> the_lot = list(x) |>> len(the_lot) == 26 ** 3 True |>> [the_lot[i] for i in (0, 1, 25, 26, -27, -26, -1)] ['aaa', 'aab', 'aaz', 'aba', 'zyz', 'zza', 'zzz'] Cheers, John -- http://mail.python.org/mailman/listinfo/python-list