首页 > 解决方案 > 无重复排列

问题描述

我正在寻找一个简单的命令/函数来生成作为 shell 命令的参数给出的数字集的排列。

在此示例中,我可以在 Python 中从 1-6 个数字生成所有 6 个数字排列:

root@debian:~# python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import permutations
>>> perm = permutations([1, 2, 3, 4, 5, 6], 6)
>>> for i in list(perm):
...     print i
...
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 6, 5)
(1, 2, 3, 5, 4, 6)
(1, 2, 3, 5, 6, 4)
(1, 2, 3, 6, 4, 5)
(1, 2, 3, 6, 5, 4)
(1, 2, 4, 3, 5, 6)
[...]

如何以更简单的方式做到这一点,最好使用单行命令,其中可以提供所有此类数字作为参数,例如:

$ command 1 2 3 4 5 6

预期输出为:

1 2 3 4 5 6
1 2 3 4 6 5
1 2 3 5 4 6
1 2 3 5 6 4
1 2 3 6 4 5
1 2 3 6 5 4
1 2 4 3 5 6
[...]

更新:当脚本使用参数时,只打印出一行:

root@debian:~# cat permut.py
import sys
n1 = sys.argv[1]
n2 = sys.argv[2]
n3 = sys.argv[3]
n4 = sys.argv[4]
n5 = sys.argv[5]
n6 = sys.argv[6]
from itertools import combinations
comb = combinations([sys.argv[1], n2, n3, n4, n5, n6], 6)
for i in list(comb):
        print i
root@debian:~# python permut.py 1 2 3 4 5 6
('1', '2', '3', '4', '5', '6')
root@debian:~#

虽然在 scipt 中提供数字时效果很好,但为什么呢?

root@debian:~# cat permut2.py
from itertools import permutations
perm = permutations([21, 2, 30, 34, 15, 46], 6)
for i in list(perm):
        print i
root@debian:~# python permut2.py|head -10
(21, 2, 30, 34, 15, 46)
(21, 2, 30, 34, 46, 15)
(21, 2, 30, 15, 34, 46)
(21, 2, 30, 15, 46, 34)
(21, 2, 30, 46, 34, 15)
(21, 2, 30, 46, 15, 34)
(21, 2, 34, 30, 15, 46)
(21, 2, 34, 30, 46, 15)
(21, 2, 34, 15, 30, 46)
(21, 2, 34, 15, 46, 30)

也与“int(sys.argv)”不起作用:

root@debian:~# cat permut.py
import sys
n1 = int(sys.argv[1])
n2 = int(sys.argv[2])
n3 = int(sys.argv[3])
n4 = int(sys.argv[4])
n5 = int(sys.argv[5])
n6 = int(sys.argv[6])
from itertools import combinations
comb = combinations([n1, n2, n3, n4, n5, n6], 6)
for i in list(comb):
        print i
root@debian:~# python permut.py 1 2 3 4 5 6
(1, 2, 3, 4, 5, 6)
root@debian:~#

标签: python

解决方案


获取命令行参数列表,并为此列表的每个排列显示用空格分隔的单个值。

import itertools
import sys

for p in itertools.permutations(sys.argv[1:]):
    print(" ".join(p))

推荐阅读