2011-08-26 85 views
0

我有以下代碼:從列表產生組合

 

def produceCombinations(text, maximumWindowWidth) 

    combinations = [] 

    for windowWidth in range(1,maximumWindowWidth+1): 
    for startingIndex in range(len(text)-windowWidth+1): 
     combinations.append((text[startingIndex:startingIndex+windowWidth])) 

    return combinations 

produceCombinations(("1","2","3","4","5","6",),3) 

這給下面的輸出:

 
('1',) 
('2',) 
('3',) 
('4',) 
('5',) 
('6',) 
('1', '2') 
('2', '3') 
('3', '4') 
('4', '5') 
('5', '6') 
('1', '2', '3') 
('2', '3', '4') 
('3', '4', '5') 
('4', '5', '6') 

不過,我也希望這個算法給我額外的組合:

 
('1', '3') # hop of 1 
('2', '4') 
('3', '5') 
('4', '6') 
('1', '4') # hop of 2 
('2', '5') 
('3', '6') 
('4', '7') 
('1', '3', '4') # hop of 1 and 0 
('2', '4', '5') 
('3', '5', '6') 
('1', '2', '4') # hop of 0 and 1 
('2', '3', '5') 
('3', '4', '6') 
('1', '3', '5') # hop of 1 and 1 
('2', '4', '6') 
('1', '2', '5') # hop of 0 and 2 
('2', '3', '6') 
('1', '3', '6') # hop of 1 and 2 
('1', '4', '5') # hop of 2 and 0 
('2', '5', '6') 
('1', '4', '6') # hop of 2 and 1 

其中我的函數將有一個新的參數稱爲maximumHop,以限制第另外還有其他組合。對於上面的例子,maximumHop是兩個,因爲組合('1','5')是不可能的。

有關一個很好的方法來做到這一點的任何建議?

感謝,

巴里

回答