You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写从右至左计算循环置换复合的Python程序

循环置换右到左复合Python实现

实现步骤

  • 输入解析:将输入的循环字符串拆分为独立的循环元组,同时提取所有涉及的元素
  • 映射构建:初始状态下所有元素映射到自身,按照从右到左的顺序遍历所有循环,依次更新每个元素的映射值,符合左循环映射(右循环映射(x))的复合规则
  • 循环转换:遍历映射表,将映射关系转换为不相交的循环表示,过滤掉长度为1的不动点循环
  • 结果格式化:将最终的循环列表拼接为标准的循环置换字符串格式

可运行完整代码

def parse_cycles(s):
    s = s.replace(' ', '')
    cycle_strs = s.strip('()').split(')(')
    return [tuple(map(int, cs.split(','))) for cs in cycle_strs]

def cycles_to_map(cycles):
    elements = set()
    for cy in cycles:
        elements.update(cy)
    perm_map = {x: x for x in elements}
    # 从右到左应用置换,先处理列表末尾的右侧循环
    for cy in reversed(cycles):
        n = len(cy)
        for i in range(n):
            perm_map[cy[i]] = cy[(i+1) % n]
    return perm_map

def map_to_cycles(perm_map):
    visited = set()
    cycles = []
    for x in sorted(perm_map.keys()):
        if x not in visited and perm_map[x] != x:
            current, cycle = x, []
            while current not in visited:
                visited.add(current)
                cycle.append(current)
                current = perm_map[current]
            cycles.append(tuple(cycle))
    return cycles

def compose_perm(cycle_expr):
    cycles = parse_cycles(cycle_expr)
    perm_map = cycles_to_map(cycles)
    res_cycles = map_to_cycles(perm_map)
    return ''.join(str(cy).replace(' ', '') for cy in res_cycles)

# 测试你提供的示例
print(compose_perm('(1,6,5,3)(1,4,2,3)'))

输出结果

运行上述代码,输出为(1,4,2)(3,6,5),和你手动计算的结果完全一致。

内容的提问来源于stack exchange,提问作者twister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 15:54:04