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中使用HTMLParser解析html实例

前几天遇到一个问题,需要把网页中的一部分内容挑出来,于是找到了urllib和HTMLParser两个库.urllib可以将网页爬下来,然后交由HTMLParser解析,初次使用这个库,在...

Python中如何获取类属性的列表

前言 最近工作中遇到个需求是要得到一个类的静态属性,也就是说有个类 Type ,我要动态获取 Type.FTE 这个属性的值。 最简单的方案有两个: getattr(Type, 'F...

浅述python中argsort()函数的实例用法

浅述python中argsort()函数的实例用法

由于想使用python用训练好的caffemodel来对很多图片进行批处理分类,学习过程中,碰到了argsort函数,因此去查了相关文献,也自己在python环境下进行了测试,大概了解了...

matplotlib.pyplot画图并导出保存的实例

我就废话不多说了,直接上代码吧! import pandas as pd import numpy as np import matplotlib.pyplot as plt fig...

Python使用__new__()方法为对象分配内存及返回对象的引用示例

Python使用__new__()方法为对象分配内存及返回对象的引用示例

本文实例讲述了Python使用__new__()方法为对象分配内存及返回对象的引用。分享给大家供大家参考,具体如下: demo.py(__new__方法): class MusicP...