Home >Backend Development >Python Tutorial >How Can I Generate Permutations with Unique Values, Avoiding Duplicates?

How Can I Generate Permutations with Unique Values, Avoiding Duplicates?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 06:20:25721browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn