屠焱,长垣结衣,手机导航系统
本文为大家分享了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 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论