Home >Backend Development >Python Tutorial >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:
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!