Reputation: 13125
I have the following code:
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)
which gives the following output:
('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')
However I also want this algorithm to give me the additional combinations:
('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
where my function will have a new argument called maximumHop so as to limit the number of these extra combinations. For the above example the maximumHop is two since the combination ('1', '5') is not possible.
Any suggestions regarding a nice way to do this?
Thanks,
Barry
Upvotes: 0
Views: 1284
Reputation: 16037
use itertools see http://docs.python.org/library/itertools.html#itertools.combinations
Upvotes: 1