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依赖包及其版本号信息的方法

查看Python依赖包及其版本号信息的方法

查看依赖包及对应的版本号信息的方法有两种: 方法1:pip list 方法2:pip freeze 这两个同时适用于Windows和Linux系统 当pip版本过低时,会出现list命...

python strip()函数 介绍

描述 Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。 语法 strip()方法语法: str.strip([chars]); 参数 chars -- 移除...

Python自动化运维之IP地址处理模块详解

实用的IP地址处理模块IPy 在IP地址规划中,涉及到计算大量的IP地址,包括网段、网络掩码、广播地址、子网数、IP类型等 别担心,Ipy模块拯救你。Ipy模块可以很好的辅助我们高效的...

用Python+OpenCV对比图像质量的几种方法

用Python+OpenCV对比图像质量的几种方法

前言 图片的本质就是大量像素在二维平面上的组合,每个像素点用数字化方式记录颜色。可以直观的想象,一张图片就是一个巨大的电子栅格,每个格子内有一盏灯泡,这个灯泡可以变换256的三次方种颜色...

python3 实现一行输入,空格隔开的示例

相信很多人都会使用 a=input() b=input() 来进行输入操作, 但是,这是以换行进行操作的,而有些题目是需要进行一行输入,空格隔开的,这时候就需要变换输入方式了。 那...