开发者

Starting value for Pythonic generator over possible letter combinations

I am trying to (1) iterate over all possible combinations of letters and (2) remembering where I left of.

E.g. a,b, c, d, ... z, aa, ab, ac, ad, ..., zz, aaa, ...

The first part is working, using the following code:

def xselections(items, n):
    if n==0: yield []
    else:
        for i in xrange(len(items)):
            for ss in xselections(items, n-1):
                yield [items[i]]+ss
for i in [1, 2, 3]: 
    for combo in xselections(ascii_lowercase, i):
        print ''.join(combo)

But I am not able to get the iteration started somewhere else, i.e. always a, b, c, ...Is there a clean way to expand the generator so that something like

xselections(items=ascii_lowercase, n=3, last=[a,c,y])
-> acz, ada, adb, adc, ...

is possible? I am looking at itertools开发者_JS百科, but not seeing the light...


This should do the job:

import itertools

letters = [ chr(l) for l in range(ord('a'), ord('z')+1) ]

def combinations(skip_to=None):
    combinations = ( itertools.combinations_with_replacement(letters, k) for k in range(1, len(letters)+1) )
    flat = itertools.chain.from_iterable( combinations )
    return flat if skip_to is None else itertools.dropwhile( lambda x: x != skip_to, flat )

The itertools module is magic indeed:-)


I know its not quite what you're looking for, but I wrote a function thats a one-to-one correspondence from int to letter sequences like you specified

def intToLetterSeq(x):
a = list()
while(x >= 0):
    a += [x % 26]
    x /= 26
    x -= 1
return [chr(97+i) for i in a[::-1]]

>>> intToLetterSeq(0)
['a']
>>> intToLetterSeq(25)
['z']
>>> intToLetterSeq(37)
['a', 'l']
>>> intToLetterSeq(11*26**3+7*26**2+2*26+20)
['k', 'g', 'b', 'u']

So that should make picking it up from random spot a little easier

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜