Python permutations with constraints

前端 未结 3 1974
忘了有多久
忘了有多久 2020-12-24 15:51

I am using python 3 and I am trying to find a way to get all the permutations of a list while enforcing some constraints.

For instance, I have a list L=[1, 2,

3条回答
  •  臣服心动
    2020-12-24 16:33

    This approach filters permutations using a simple filter.

    import itertools
    
    groups = [(1,2),(3,4,5),(6,7)]
    groupdxs = [i for i, group in enumerate(groups) for j in range(len(group))]
    old_combo = []
    for dx_combo in itertools.permutations(groupdxs):
        if dx_combo <= old_combo: # as simple filter
            continue
        old_combo = dx_combo
        iters = [iter(group) for group in groups]
        print [next(iters[i]) for i in dx_combo]
    

    What we are doing here is finding permutations of a multiset. (In this case the multiset is groupdxs.) Here's a paper that details an O(1) algorithm for this.

提交回复
热议问题