python - 不包括逆的排列

标签 python permutation

我需要获得排列,排除镜像序列,即应包含 (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

最佳答案

假设iterable中的条目是唯一且可排序的,我将简单地比较排列的任意两个元素(例如第一个和最后一个),并且仅包括第一个元素较少的那些排列或等于最后一个元素。这样,您就不需要存储已经看到的内容,也不必关心 itertools.permutations() 返回排列的顺序。

示例代码:

def permutations_no_inverse(iterable):
    for p in itertools.permutations(iterable):
        if p[0] <= p[-1]:
            yield p

关于python - 不包括逆的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46342793/

相关文章:

python - 如何使用 pygame 播放 mp3?

python - 重新排列字符串/列表的所有方法的列表

c# - 即使在 ".ToList()"调用之后,递归中的 yield 返回也不会返回值

java - 将整数排列的完整 ArrayLists 排序为决策树结构

C++:递归计算数字 0 - 9 的所有排列

c++ - 需要参数的函数无需参数即可工作 (C++)

python - 获取生成器的子集

python - Python 中的 Selenium webdriver 屏幕截图分辨率错误

python - IntegrityError :NOT NULL constraint failed: chatapp_chat. 消息

python - 如何在python中将字符串转换为正则表达式?