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、约束函数的调用者必须按照Kye...

两个元祖T1=('a', 'b'),T2=('c', 'd')使用匿名函数将其转变成[{'a': 'c'},{'b': 'd'}]的几种方法

一道Python面试题的几种解答: 两个元祖T1=('a', 'b'), T2=('c', 'd'),请使用匿名函数将其转变成[{'a': 'c'}, {'b': 'd'}] 方法一:...

python实现windows倒计时锁屏功能

python实现windows倒计时锁屏功能 # 倒计时锁屏 import time from ctypes import * def closewindows(closetime)...

对python中字典keys,values,items的使用详解

在python中对字典进行遍历时,可以直接使用如下模式: dict = {"name": "jack", "age": 15, "height": 1.75} for k...

python创建临时文件夹的方法

本文实例讲述了python创建临时文件夹的方法。分享给大家供大家参考。具体实现方法如下: import tempfile, os tempfd, tempname = tempfi...