Home > Backend Development > Python Tutorial > How Can I Generate Permutations with Unique Values in Python?

How Can I Generate Permutations with Unique Values in Python?

Barbara Streisand
Release: 2024-12-04 17:05:12
Original
242 people have browsed it

How Can I Generate Permutations with Unique Values in Python?

Permutations with Unique Values

The provided Python code faces an issue with generating permutations using itertools.permutations, where elements are considered unique based on their position, leading to repeated values.

To address this, sympy offers an optimized iterator, multiset_permutations. This iterator directly generates permutations that recognize values as unique, disregarding their order.

Below is an example demonstrating the use of multiset_permutations to obtain permutations with unique values:

from sympy.utilities.iterables import multiset_permutations

permutations = list(multiset_permutations([1,1,1]))
print(permutations)  # Output: [[1, 1, 1]]
Copy after login

In this case, the output correctly reflects that there is only one unique permutation resulting from the unique values in the input.

The above is the detailed content of How Can I Generate Permutations with Unique Values in Python?. 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