Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the python equivalent to perl "a".."azc"

Tags:

python

list

perl

In perl, to get a list of all strings from "a" to "azc", to only thing to do is using the range operator:

perl -le 'print "a".."azc"'

What I want is a list of strings:

["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"]

I suppose I can use ord and chr, looping over and over, this is simple to get for "a" to "z", eg:

>>> [chr(c) for c in range(ord("a"), ord("z") + 1)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

But a bit more complex for my case, here.

Thanks for any help !

like image 586
Alexis Métaireau Avatar asked Jul 16 '10 11:07

Alexis Métaireau


3 Answers

Generator version:

from string import ascii_lowercase
from itertools import product

def letterrange(last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            yield result
            if result == last:
                return

EDIT: @ihightower asks in the comments:

I have no idea what I should do if I want to print from 'b' to 'azc'.

So you want to start with something other than 'a'. Just discard anything before the start value:

def letterrange(first, last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            if first:
                if first != result:
                    continue
                else:
                    first = None
            yield result
            if result == last:
                return
like image 166
Mike DeSimone Avatar answered Nov 07 '22 20:11

Mike DeSimone


A suggestion purely based on iterators:

import string
import itertools

def string_range(letters=string.ascii_lowercase, start="a", end="z"):
    return itertools.takewhile(end.__ne__, itertools.dropwhile(start.__ne__, (x for i in itertools.count(1) for x in itertools.imap("".join, itertools.product(letters, repeat=i)))))

print list(string_range(end="azc"))
like image 4
Philipp Avatar answered Nov 07 '22 20:11

Philipp


Use the product call in itertools, and ascii_letters from string.

from string import ascii_letters
from itertools import product

if __name__ == '__main__':
    values = []
    for i in xrange(1, 4):
        values += [''.join(x) for x in product(ascii_letters[:26], repeat=i)]

    print values
like image 2
muckabout Avatar answered Nov 07 '22 21:11

muckabout