生成具有唯一值的排列
使用 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中文网其他相关文章!