Increase row size through loop

What is a simple way to increase the length of a string to an arbitrary integer x? for example, 'a' goes into 'z' and then goes to 'aa' in 'zz' in 'aaa', etc.

+5
source share
4 answers

This 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

He returns the generator. You can iterate with a for loop:

for s in iterate_strings(5)

Or get a list of strings:

list(iterate_strings(5))

If you want to iterate over shorter lines, 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
+6
source

Here is my solution, similar to Adam, except for it is 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 generator, so you can use a loop forto iterate over it:

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

Good luck

( , itertools.product() . Woot.)

+2

.

>>> 'a' * 2
'aa'
>>> 'a' * 4
'aaaa'
>>> 'z' * 3
'zzz'
>>> 'az' * 3
'azazaz'
0

Define x. I use x = 5for this example.

x = 5
import string
for n in range(1,x+1):
  for letter in string.ascii_lowercase:
    print letter*n
0
source

All Articles