Most elegant way to generate 3-char sequence

Rob Cowie cowie.rob at gmail.com
Sat Jun 10 05:01:24 EDT 2006


John Machin wrote:
> 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.
Not sure I understand your point. Why would I forget the alphabet?

> Why type all that punctuation?
What punctuation?

> Any reason this cruft is global (i.e. not local to the generator)?
No

>
> > alpha2 = ['a','b','c','d']
> > alpha3 = ['a','b','c','d']
>
> Hope you get the redundant copy/paste right.
Again, I don't understand what you mean

>
> >
> > def generator():
> >   for char in alpha:
>
> Why stop at two spaces? One-space indentation is syntactically correct :-)
As are 3, 4 and 5 space indentation. Yet again, what is your point?

>
> >     for char2 in alpha2:
> >       for char3 in alpha3:
> >         yield char + char2 + char3
> >
> > x = generate()
>
> Did you meant "generator"?
Yes, made a mistake
>
> > 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

I'm aware the code I posted is not great - it isn't code I would
consider using. It was only intended to serve as an illustration of the
task at hand in case my explanation wasn't sufficient.

I'm grateful to you for using list(generator) in your example. I was
not aware this could be done (I haven't yet fully read the generator
documentation).

Rob C




More information about the Python-list mailing list