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

How to Generate Permutations with Unique Values, Avoiding Duplicates?

DDD
DDDOriginal
2024-12-06 04:25:15485browse

How to Generate Permutations with Unique Values, Avoiding Duplicates?

Generating Permutations with Unique Values

Permutations generated using the itertools.permutations() function treat elements as unique based on position, not value. Consequently, it can produce duplicates that differ only in the order of elements with the same value.

Solution

To avoid duplicates, consider using the following approach:

  1. Utilize the sympy library's multiset_permutations() iterator, which explicitly handles values as unique regardless of position.
  2. Alternatively, implement a non-iterative algorithm that tracks the frequency of each unique value:
def unique_permutations(elements):
    """Generate permutations with unique values."""
    elements = sorted(elements)
    result = []
    counts = {}
    prev_element = None
    for element in elements:
        if element != prev_element:
            counts[element] = 1
        else:
            counts[element] += 1
        result.extend(combine(element, counts))
        prev_element = element
    return result

def combine(element, counts):
    """Combine element with unique counts to form permutations."""
    permutations = []
    if sum(counts.values()) == 1:
        return [tuple([element])]
    for other_element, count in counts.items():
        if element == other_element:
            count -= 1
        permutations.extend([*tuple([element]), *sublist] for sublist in combine(other_element, count))
    return permutations

Example

>>> list(unique_permutations([1, 1, 2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]

The above is the detailed content of How to 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