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
Release: 2024-12-17 06:20:25
Original
715 people have browsed it

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]]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template