python3数字全排列怎么搞_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使用遞歸解決全排列數字示例
本文地址: http://www.cppcns.com/jiaoben/python/104923.html
總結
以上是生活随笔為你收集整理的python3数字全排列怎么搞_python使用递归解决全排列数字示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python项目实战_2个Python入
- 下一篇: python动态改变标签的颜色_PyQt