Python实现全排列的打印

yipeiwu_com6年前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实现筛选文件脚本的方法

在做项目时遇到需要标记数据集里面的若干图片数据,作为程序员,为避免手动一张一张的筛选,所以写了这个Python脚本实现。 Python脚本如下: # from PIL import...

selenium使用chrome浏览器测试(附chromedriver与chrome的对应关系表)

selenium使用chrome浏览器测试(附chromedriver与chrome的对应关系表)

使用WebDriver在Chrome浏览器上进行测试时,需要从http://chromedriver.storage.googleapis.com/index.html网址中下载与本机c...

在Python中用get()方法获取字典键值的教程

 get()方法返回给定键的值。如果键不可用,则返回默认值None。 语法 以下是get()方法的语法: dict.get(key, default=None) 参数...

python 实现生成均匀分布的点

如下所示: import numpy as np print(np.linspace(-100,100,201) np.linspace(),起始位置,终止位置,中间包括0,一共要...

python实现下载pop3邮件保存到本地

python实现下载pop3邮件保存到本地

利用python进行unix管理一书中有一个登陆下载邮箱的脚本,实练了下还不错,对于邮箱备份来说还是比较快捷的,但是其命名方式是以编号和 文件大小来命名的,不方便阅读,于是进行了改进修改...