在 Python 中生成不带反转序列的排列

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)))
2个回答

3
为了简化您的代码并使其更高效,您可以:
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集合的建议。 - nico

3
你可以只使用每个反转对中较小的那个:
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

1
非常优雅的解决方案! - nico

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接