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版本的仿windows计划任务工具

python版本的仿windows计划任务工具

计划任务工具-windows 计划任务工具根据自己设定的具体时间,频率,命令等属性来规定所要执行的计划。 效果图 代码 # -*- coding: utf-8 -*- """ M...

python 美化输出信息的实例

python 美化输出信息的实例

如下所示: # -*- coding: utf-8 -*- # @Author: xiaodong # @Date: just hide # @Last Modified by:...

Python 3.3实现计算两个日期间隔秒数/天数的方法示例

Python 3.3实现计算两个日期间隔秒数/天数的方法示例

本文实例讲述了Python 3.3实现计算两个日期间隔秒数/天数的方法。分享给大家供大家参考,具体如下: >>> import datetime >>&...

python数值基础知识浅析

内置数据类型 Python的内置数据类型既包括数值型和布尔型之类的标量,也包括 更为复杂的列表、字典和文件等结构。 数值 Python有4种数值类型,即整数型、浮点数型、复数型和布...

Python GUI编程完整示例

Python GUI编程完整示例

本文实例讲述了Python GUI编程。分享给大家供大家参考,具体如下: import os from time import sleep from tkinter import *...