【问题标题】:Permutations without reversed sequences in PythonPython中没有反向序列的排列
【发布时间】:2021-11-12 13:37:16
【问题描述】:

我想生成一个所有 4 位数字排列的列表,其中:

  • 始终存在所有 4 位数字
  • 两个相反的序列是相同的解决方案。例如。 (1,2,3,4) = (4,3,2,1)

我想知道:

  • 你怎么称呼这种排列。
  • 如果可以一步生成此列表。下面是一个分两步生成它的示例。
import itertools
inp_list = range(1, 5)

# 1. Create the list of all permutations.
permutations = list(itertools.permutations(inp_list))

# 2. Remove sequences that are the reverse of another.
for _p in permutations[::-1]:
    if _p[::-1] in permutations:
        permutations.remove(_p)

for _p in permutations:
    print("\t".join(map(str, _p)))

【问题讨论】:

    标签: python permutation


    【解决方案1】:

    为了简化您的代码并使其更高效,您可以:

    1- 使用python set 作为容器(检查元素是否存在要快得多)

    2-直接添加最终输出

    3- 避免使用排列创建临时列表,将其保留为生成器

    from itertools import permutations
    inp_list = range(1, 5)
    
    out = set()
    for p in permutations(inp_list): # loop over generator output
        p = '\t'.join(map(str,p))    # craft the desired output format
        if not p[::-1] in out:       # is the reverse not already in the set?
            out.add(p)               # then add the item
            print(p)                 # and print it
    

    输出:

    1   2   3   4
    1   2   4   3
    1   3   2   4
    1   3   4   2
    1   4   2   3
    1   4   3   2
    2   1   3   4
    2   1   4   3
    2   3   1   4
    2   4   1   3
    3   1   2   4
    3   2   1   4
    

    【讨论】:

    • 感谢您对 python 集的建议。
    【解决方案2】:

    您可以只使用每个反转对中较小的一个:

    from itertools import permutations
    
    for p in permutations(range(1, 5)):
        if p < p[::-1]:
            print(*p)
    

    输出:

    1 2 3 4
    1 2 4 3
    1 3 2 4
    1 3 4 2
    1 4 2 3
    1 4 3 2
    2 1 3 4
    2 1 4 3
    2 3 1 4
    2 4 1 3
    3 1 2 4
    3 2 1 4
    

    【讨论】:

    • 非常优雅的解决方案!
    猜你喜欢
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2015-05-16
    • 2010-10-31
    相关资源
    最近更新 更多