python使用递归解决全排列数字示例
2014-02-11 00:00
786 查看
第一种方法:递归
结果
第二种方法: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-8import 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基础教程之实现石头剪刀布游戏示例
- python网络爬虫采集联想词示例
- python重试装饰器示例
- python中的yield使用方法
- Python的print用法示例
- 优秀Python学习资源
- Python学习笔记(1)
- 优秀Python学习资源收集汇总(强烈推荐)
- [Python] The project structure in Django
- python - django - 初步认识
- 优秀Python学习资源收集汇总(强烈推荐)
- Python_C4_作出决策【上】
- Python菜鸟学习第三课
- Python字典排序的简单实现
- python中单引号,双引号,多引号区别
- Python_C3_变量【下】
- python:UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xef in position xxx: ordinal not in range(128)
- python 字符串转时间
- MySQL-python
- PHP / Web / Python