permutations with unique values

前端 未结 19 1677
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:53

itertools.permutations generates where its elements are treated as unique based on their position, not on their value. So basically I want to avoid duplicates like this:

19条回答
  •  醉梦人生
    2020-11-22 02:23

    Bumped into this question while looking for something myself !

    Here's what I did:

    def dont_repeat(x=[0,1,1,2]): # Pass a list
        from itertools import permutations as per
        uniq_set = set()
        for byt_grp in per(x, 4):
            if byt_grp not in uniq_set:
                yield byt_grp
                uniq_set.update([byt_grp])
        print uniq_set
    
    for i in dont_repeat(): print i
    (0, 1, 1, 2)
    (0, 1, 2, 1)
    (0, 2, 1, 1)
    (1, 0, 1, 2)
    (1, 0, 2, 1)
    (1, 1, 0, 2)
    (1, 1, 2, 0)
    (1, 2, 0, 1)
    (1, 2, 1, 0)
    (2, 0, 1, 1)
    (2, 1, 0, 1)
    (2, 1, 1, 0)
    set([(0, 1, 1, 2), (1, 0, 1, 2), (2, 1, 0, 1), (1, 2, 0, 1), (0, 1, 2, 1), (0, 2, 1, 1), (1, 1, 2, 0), (1, 2, 1, 0), (2, 1, 1, 0), (1, 0, 2, 1), (2, 0, 1, 1), (1, 1, 0, 2)])
    

    Basically, make a set and keep adding to it. Better than making lists etc. that take too much memory.. Hope it helps the next person looking out :-) Comment out the set 'update' in the function to see the difference.

提交回复
热议问题