2011-04-02 16 views
1

我試圖(1)遍歷所有可能的字母組合並(2)記住我離開的位置。Pythonic發生器在可能的字母組合上的起始值

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

第一部分工作,使用下面的代碼:

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) 

但我沒能獲得迭代開始在其他地方,即總是,B,C,...是有沒有乾淨的方式來擴大發生器,使像

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

是可能的嗎?我在看itertools,但沒有看到光...

+1

你知道生成器,但使用'xrange(len(...))'遍歷事物嗎? – delnan 2011-04-03 00:01:49

+0

你想通過記住你離開的地方來達到什麼目的?提取一些值然後提取更多或僅跳過一些第一個值? – pajton 2011-04-03 00:04:37

+0

@pajton如果需要,我想跳過第一個值。 – mhermans 2011-04-03 00:47:53

回答

2

這應該做的工作:

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) 

itertools模塊是魔術的確:-)

2

我知道它並不完全符合你要找的,但我寫的像你指定

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'] 

所以,應該讓一個函數從int到字母序列那是一一一對應從隨機點輕鬆取出它更容易