Home >Backend Development >Python Tutorial >How Can I Generate Permutations with Unique Values, Avoiding Duplicates?
Generating Permutations with Unique Values
Itertools' permutations function treats elements as unique based on position rather than value, resulting in duplicates. To address this challenge, an algorithm is sought to avoid such duplicates.
One approach involves utilizing sympy's multiset_permutations iterator. This iterator generates permutations while considering element values rather than positions:
>>> import sympy >>> from sympy.utilities.iterables import multiset_permutations >>> list(multiset_permutations([1,1,1])) [[1, 1, 1]] >>> list(multiset_permutations([1,1,2])) [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
This effectively addresses the issue of duplicate permutations, providing a concise and efficient solution.
The above is the detailed content of How Can I Generate Permutations with Unique Values, Avoiding Duplicates?. For more information, please follow other related articles on the PHP Chinese website!