这篇文章主要介绍Python如何实现全排列的打印,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
问题:输入一个数字:3,打印它的全排列组合:123 132 213 231 312 321,并进行统计个数。
下面是Python的实现代码:
#!/usr/bin/env python
# -*- coding: <encoding name> -*-
'''
全排列的demo
input : 3
output:123 132 213 231 312 321
'''
total = 0
def permutationCove(startIndex, n, numList):
'''递归实现交换其中的两个。一直循环下去,直至startIndex == n
'''
global total
if startIndex >= n:
total += 1
print numList
return
for item in range(startIndex, n):
numList[startIndex], numList[item] = numList[item], numList[startIndex]
permutationCove(startIndex + 1, n, numList )
numList[startIndex], numList[item] = numList[item], numList[startIndex]
n = int(raw_input("please input your number:"))
startIndex = 0
total = 0
numList = [x for x in range(1,n+1)]
print '*' * 20
for item in range(0, n):
numList[startIndex], numList[item] = numList[item], numList[startIndex]
permutationCove(startIndex + 1, n, numList)
numList[startIndex], numList[item] = numList[item], numList[startIndex]
print total
以上是“Python如何实现全排列的打印”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。