views:

84

answers:

4

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.

A: 

You can multiply the string in the integer. For example

>>> 'a' * 2
'aa'
>>> 'a' * 4
'aaaa'
>>> 'z' * 3
'zzz'
>>> 'az' * 3
'azazaz'
Adam
yes, but i want to run through all the permutations
calccrypto
Let's see if I get you right: You want to iterate over all the strings between 'aaaa' and 'zzzz', ('aaaa', 'aaab', 'aaac', .... 'zzzz').
Adam
correct. all the way until the string is x chars long
calccrypto
A: 

Define x. I am using x = 5 for this example.

x = 5
import string
for n in range(1,x+1):
  for letter in string.ascii_lowercase:
    print letter*n
tdedecko
You might want to set the start value of the range statement since the very first thing printed using that code is 26 lines of blanks because you're doing `letter*0` at first.
Dustin
Very true. Fixed.
tdedecko
+4  A: 

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
Adam
even though it goes backwards, cool!
calccrypto
Fixed the backwards going problem.Vote for my answer please :)
Adam
i tried, but apparently i need 15 reputation
calccrypto
A: 

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.)

Xavier Ho