產生具有唯一值的排列
使用itertools.permutations() 函數產生的排列將元素視為基於位置的唯一元素,而不是基於值。因此,它可能會產生僅在具有相同值的元素順序上有所不同的重複項。
解決方案
要避免重複,請考慮使用以下方法:
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
範例
>>> list(unique_permutations([1, 1, 2])) [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
以上是如何產生具有唯一值的排列,避免重複?的詳細內容。更多資訊請關注PHP中文網其他相關文章!