生成排列的所有一步变体

时间:2013-08-28 22:28:34

标签: python permutation itertools

我只是想知道是否有更动态的方式从给定的排列中获得一步变化而不是指定每一步。我打算做的是如果我让我们说“(0,0,0,0,0,)”的排列,我指定一个选择的可能性作为范围选择,所以在这种情况下我指定了范围到是5,选项将是“0,1,2,3,4”,我想生成如下所示的排列:(1,0,0,0,0),(2,0,0,0,0 ),(3,0,0,0,0)等等,你一次只能改变一个元素我该怎么做。任何帮助都会很棒!

2 个答案:

答案 0 :(得分:2)

不完全确定你在寻找什么......也许是这样的,

def single_element_permutation(given, new):
    for i in xrange(len(given)):
        for ele in new:
            yield given[:i] + (ele,) + given[i+1:]

for e in single_element_permutation((0, 0, 0, 0, 0), range(5)):
    print e

输出:

(0, 0, 0, 0, 0)
(1, 0, 0, 0, 0)
(2, 0, 0, 0, 0)
(3, 0, 0, 0, 0)
(4, 0, 0, 0, 0)
(0, 0, 0, 0, 0)
(0, 1, 0, 0, 0)
(0, 2, 0, 0, 0)
(0, 3, 0, 0, 0)
(0, 4, 0, 0, 0)
(0, 0, 0, 0, 0)
(0, 0, 1, 0, 0)
(0, 0, 2, 0, 0)
(0, 0, 3, 0, 0)
(0, 0, 4, 0, 0)
(0, 0, 0, 0, 0)
(0, 0, 0, 1, 0)
(0, 0, 0, 2, 0)
(0, 0, 0, 3, 0)
(0, 0, 0, 4, 0)
(0, 0, 0, 0, 0)
(0, 0, 0, 0, 1)
(0, 0, 0, 0, 2)
(0, 0, 0, 0, 3)
(0, 0, 0, 0, 4)

答案 1 :(得分:0)

>>> from itertools import product
>>> for p in product(range(5), repeat=5):
    print(p[::-1])
(0, 0, 0, 0, 0)
(1, 0, 0, 0, 0)
(2, 0, 0, 0, 0)
(3, 0, 0, 0, 0)
(4, 0, 0, 0, 0)
(0, 1, 0, 0, 0)
(1, 1, 0, 0, 0)
....
>>> import itertools
>>> for p in itertools.permutations(range(5)):
    print(p[::-1])
(4, 3, 2, 1, 0)
(3, 4, 2, 1, 0)
(4, 2, 3, 1, 0)
(2, 4, 3, 1, 0)
(3, 2, 4, 1, 0)
....
>>> for p in itertools.combinations_with_replacement(range(5), 5):
    print(p)
(0, 0, 0, 0, 0)
(0, 0, 0, 0, 1)
(0, 0, 0, 0, 2)
(0, 0, 0, 0, 3)
(0, 0, 0, 0, 4)
(0, 0, 0, 1, 1)
....

那样的?沿着这些路线? :P

相关问题