Python实现全排列的打印

yipeiwu_com5年前Python基础

本文为大家分享了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设计】。

相关文章

python顺序执行多个py文件的方法

假如我要执行code目录下的python程序,假设该目录下有1.py,2.py,3.py,4.py四个文件,但是我想执行1.py,2.py,4.py,则可在该目录下创建一个python文...

python pandas写入excel文件的方法示例

pandas读取、写入csv数据非常方便,但是有时希望通过excel画个简单的图表看一下数据质量、变化趋势并保存,这时候csv格式的数据就略显不便,因此尝试直接将数据写入excel文件。...

python pyinstaller打包exe报错的解决方法

python pyinstaller打包exe报错的解决方法

今天用python 使用pyinstaller打包exe出现错误 环境pyqt5 + python3.6 32位 在导入pyqt5包之前加上如下代码 import sys impo...

python安装gdal的两种方法

1.不用手动下载文件,直接执行以下命令即可 conda install gdal 2.首先,下载gdal的whl文件  链接, 官网下载比较慢,GDAL-2.2.4-cp27-...

python打开文件并获取文件相关属性的方法

本文实例讲述了python打开文件并获取文件相关属性的方法。分享给大家供大家参考。具体分析如下: 下面的代码通过open函数打开文件,并输出文件名、打开状态、打开模式等属性 #!/u...