从列表中生成组合

时间:2011-08-26 18:25:21

标签: python-3.x

我有以下代码:


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是2,因为组合('1','5')是不可能的。

有关这种方法的好建议吗?

谢谢,

百里

1 个答案:

答案 0 :(得分:1)