Find the index of a given combination (of natural numbers) among those returned by `itertools` Python module

前端 未结 3 1058
无人共我
无人共我 2021-01-05 08:01

Given a combination of k of the first n natural numbers, for some reason I need to find the position of such combination among those returned by

3条回答
  •  甜味超标
    2021-01-05 08:44

    Looks like you need to better specify your task or I am just getting it wrong. For me it seems that when you iterating through the itertools.combination you can save indexes you need to an appropriate data structure. If you need all of them then I would go with the dict (one dict for all your needs):

    combinationToIdx = {}
    for (idx, comb) in enumerate(itertools.combinations(range(1,14),6)):
        combinationToIdx[comb] = idx
    
    def findIdx(comb):
        return combinationToIdx[comb]
    

提交回复
热议问题