Skip to main content
 首页 » 编程设计

python之不包括逆的排列

2024年10月01日7findumars

<分区>

我需要得到排列,不包括镜像序列,即应该包括 (1, 0, 4),但之后应该排除 (4, 0, 1)。 我想出了以下功能,但想知道是否有更简单的解决方案。

该函数基于它们的最后一个元素与相应序列的第一个元素相同的事实跳过逆元素,该序列已经按照给定的字典顺序进行了处理。

def permutations_no_inverse(iterable):     
    """Return the half of permutations, treating mirrored sequences as the same, 
    e.g. (0, 1, 2) and (2, 1, 0) are the same. 
    Assume itertools.permutations returns tuples 
    """ 
 
    all_perm = it.permutations(iterable) 
    cur_start = None  
    starts_processed = set() 
    for perm in all_perm: 
        new_start = perm[0]  
        if new_start != cur_start: 
            if cur_start != None: 
                starts_processed.add(cur_start) 
            cur_start = new_start 
        if perm[-1] in starts_processed: 
            continue 
        else: 
            yield perm