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

yipeiwu_com5年前Python基础

第一种方法:递归

复制代码 代码如下:

def perms(elements):
    if len(elements) <=1:
        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) <=1:
        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

相关文章

Python基于FTP模块实现ftp文件上传操作示例

本文实例讲述了Python基于FTP模块实现ftp文件上传操作。分享给大家供大家参考,具体如下: #!/usr/bin/python #-*- coding:utf-8 -*- fr...

Python的Tornado框架异步编程入门实例

Python的Tornado框架异步编程入门实例

Tornado Tornado 是一款非阻塞可扩展的使用Python编写的web服务器和Python Web框架, 可以使用Tornado编写Web程序并不依赖任何web服务器直接提供高...

pip命令无法使用的解决方法

今天在学习Python时需要安装Requests    使用命令:pip install requests    &...

Python工程师面试题 与Python Web相关

本文为大家分享的Python工程师面试题主要与Python Web相关,供大家参考,具体内容如下 1、解释一下 WSGI 和 FastCGI 的关系? CGI全称是“公共网关接口”(Co...

python pygame实现滚动横版射击游戏城市之战

python pygame实现滚动横版射击游戏城市之战

pygame城市之战横版射击游戏,按上下左右方向箭头操作飞机。这是一个横板射击小游戏,在黑夜的城市上空,你将要操作一架飞机去射击敌机,爆炸效果还不错。 在游戏中定义了滚动的背景类,定义了...