Incrementing a string

exarkun at divmod.com exarkun at divmod.com
Thu Sep 16 05:52:49 CEST 2004


On Wed, 15 Sep 2004 15:08:20 -0700, John Velman <velman at cox.net> wrote:
> [snip]
> 
> In Python I can get from a to z with a generator as so:
> 
> >>> def gen_alph():
> ...     for i in range(97,123):
> ...         yield chr(i)
> ...
> >>> g = gen_alph()
> >>> g.next()
> 'a'
> >>> g.next()
> 'b'
> >>> g.next()
> 'c'
> 
> But it looks like going beyond z to aa and so on is (relatively) complicated.

  Not so complicated...  Here's how I might do it:

>>> def permute(s, n):
...     if n == 0:
...         yield ''
...     else:
...         for ch in s:
...             for rest in permute(s, n - 1):
...                 yield ch + rest
...
>>> def labels(s):
...     length = 1
...     while True:
...         for lab in permute(s, length):
...             yield lab
...         length += 1
...
>>> import itertools
>>> print list(itertools.islice(labels('abc'), 0, 20))
['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb']

  Jp



More information about the Python-list mailing list