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示例:实现保存网页到本地复制代码 代码如下:#coding=utf-8__auther__ = 'xianbao'import urllibimport osdef re...

python引入导入自定义模块和外部文件的实例

项目中想使用以前的代码,或者什么样的需求致使你需要导入外部的包 如果是web 下,比如说django ,那么你新建一个app,把你需要导入的说用东东,都写到这个app中,然后在setti...

Python远程视频监控程序的实例代码

老板由于事务繁忙无法经常亲临教研室,于是让我搞个监控系统,让他在办公室就能看到教研室来了多少人。o(>﹏<)o||| 最初我的想法是直接去网上下个软件,可是找来找去不是有毒就...

Python 可变类型和不可变类型及引用过程解析

在Python中定义一个数据便在内存中开辟一片空间来存储这个变量的值,这块已经被分配的内存空间便会有一个内存地址。访问这块内存需要用到变量名,变量名实际存储的是变量的地址在内存中的地址,...

python实现得到一个给定类的虚函数

本文实例讲述了python实现得到一个给定类的虚函数的方法,分享给大家供大家参考。具体如下: 现来看看如下代码: import wx for method in dir(wx.P...