permutations with unique values

前端 未结 19 1431
爱一瞬间的悲伤
爱一瞬间的悲伤 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:24

    Here is a recursive solution to the problem.

    def permutation(num_array):
        res=[]
        if len(num_array) <= 1:
            return [num_array]
        for num in set(num_array):
            temp_array = num_array.copy()
            temp_array.remove(num)
            res += [[num] + perm for perm in permutation(temp_array)]
        return res
    
    arr=[1,2,2]
    print(permutation(arr))
    

提交回复
热议问题