Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increasing string size through loop

Tags:

python

string

what's a simple way to increase the length of a string to an arbitrary integer x? like 'a' goes to 'z' and then goes to 'aa' to 'zz' to 'aaa', etc.

like image 979
calccrypto Avatar asked May 14 '10 23:05

calccrypto


2 Answers

That should do the trick:

def iterate_strings(n):
    if n <= 0:
        yield ''
        return
    for c in string.ascii_lowercase:
        for s in iterate_strings(n - 1):
            yield c + s

It returns a generator. You can iterate it with a for loop:

for s in iterate_strings(5)

Or get a list of the strings:

list(iterate_strings(5))

If you want to iterate over shorter strings too, you can use this function:

def iterate_strings(n):
    yield ''
    if n <= 0:
        return
    for c in string.ascii_lowercase:
        for s in iterate_strings(n - 1):
            yield c + s
like image 179
Adam Avatar answered Nov 08 '22 04:11

Adam


Here's my solution, similar to Adam's, except it's not recursive. :].

from itertools import product
from string import lowercase

def letter_generator(limit):
    for length in range(1, limit+1):
        for letters in product(lowercase, repeat=length):
            yield ''.join(letters)

And it returns a generator, so you can use a for loop to iterate over it:

for letters in letter_generator(5):
    # ...

Have fun!

(This is the second time today I found itertools.product() useful. Woot.)

like image 3
Xavier Ho Avatar answered Nov 08 '22 04:11

Xavier Ho