Home >Backend Development >Python Tutorial >python使用递归解决全排列数字示例

python使用递归解决全排列数字示例

WBOY
WBOYOriginal
2016-06-16 08:45:221294browse

第一种方法:递归

复制代码 代码如下:

def perms(elements):
    if len(elements)         yield elements
    else:
        for perm in perms(elements[1:]):
            for i in range(len(elements)):
                yield perm[:i] + elements[0:1] + perm[i:]

for item in list(perms([1, 2, 3,4])):
    print item


结果
复制代码 代码如下:

[1, 2, 3, 4]
[2, 1, 3, 4]
[2, 3, 1, 4]
[2, 3, 4, 1]
[1, 3, 2, 4]
[3, 1, 2, 4]
[3, 2, 1, 4]
[3, 2, 4, 1]
[1, 3, 4, 2]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[1, 2, 4, 3]
[2, 1, 4, 3]
[2, 4, 1, 3]
[2, 4, 3, 1]
[1, 4, 2, 3]
[4, 1, 2, 3]
[4, 2, 1, 3]
[4, 2, 3, 1]
[1, 4, 3, 2]
[4, 1, 3, 2]
[4, 3, 1, 2]
[4, 3, 2, 1]

第二种方法:python标准库

复制代码 代码如下:

import itertools
print list(itertools.permutations([1, 2, 3,4],3))

源代码如下:

复制代码 代码如下:

#coding:utf-8
import itertools
print list(itertools.permutations([1, 2, 3,4],3))

def perms(elements):
    if len(elements)         yield elements
    else:
        for perm in perms(elements[1:]):
            for i in range(len(elements)):
                yield perm[:i] + elements[0:1] + perm[i:]

for item in list(perms([1, 2, 3,4])):
    print item

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn