Python permutations with constraints

前端 未结 3 1970
忘了有多久
忘了有多久 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:23

    def partial_permutations(*groups):
        groups = list(filter(None, groups)) # remove empties.
        # Since we iterate over 'groups' twice, we need to
        # make an explicit copy for 3.x for this approach to work.
        if not groups:
            yield []
            return
        for group in groups:
            for pp in partial_permutations(*(
                 g[1:] if g == group else g
                 for g in groups
            )):
                yield [group[0]] + pp
    

提交回复
热议问题