1

我需要帮助在 python 中创建一个程序,向您展示所有可能的组合。例如:我给它数字“1 2 3”,我给我“1 3 2”、“3 2 1”、“3 1 2”、“2 1 3”、“2 3 1”。

4

2 回答 2

4

使用itertools. 它使生活变得轻松:

import itertools

perms = itertools.permutations([1,2,3])

for perm in perms:
    print perm

>>>(1, 2, 3)
>>>(1, 3, 2)
>>>(2, 1, 3)
>>>(2, 3, 1)
>>>(3, 1, 2)
>>>(3, 2, 1)
于 2013-06-06T21:20:19.750 回答
0
from itertools import combinations as c
for x in c([1, 2, 3],2): print x
(1, 2)
(1, 3)
(2, 3)
print [x for x in c(range(5), 3)]                                        
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
于 2013-06-06T21:27:44.777 回答