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读取LMDB中图像的方法

本文实例为大家分享了python读取LMDB中的图像具体代码,供大家参考,具体内容如下 图像数据写入LMDB之后最好再按照写入的逻辑反向解析写入的图像,如果图像能够被还原则证明写入方式是...

python结合opencv实现人脸检测与跟踪

python结合opencv实现人脸检测与跟踪

模式识别课上老师留了个实验,在VC++环境下利用OpenCV库编程实现人脸检测与跟踪。 然后就开始下载opencv和vs2012,再然后,配置了好几次还是配置不成功,这里不得不吐槽下微软...

Pytorch evaluation每次运行结果不同的解决

这两天跑测试图时,发现用同样的model,同样的测试图,每次运行结果不同; 经过漫长的debug发现,在net architure中有dropout,如下(4): (conv_blo...

python 找出list中最大或者最小几个数的索引方法

如下所示: nums = [1,8,2,23,7,-4,18,23,24,37,2] result = map(nums.index, heapq.nlargest(3, nums)...

python使用matplotlib模块绘制多条折线图、散点图

python使用matplotlib模块绘制多条折线图、散点图

今天想直观的展示一下数据就用到了matplotlib模块,之前都是一张图只有一条曲线,现在想同一个图片上绘制多条曲线来对比,实现很简单,具体如下: #!usr/bin/env pyt...