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设计】。

相关文章

PyQt5根据控件Id获取控件对象的方法

如下所示: self.findChild(QComboBox, "name") self is class first parameter is Type second pa...

Python3实现zip分卷压缩过程解析

Python3实现zip分卷压缩过程解析

使用zipfile库 查看 官方中文文档 利用 Python 压缩 ZIP 文件,我们第一反应是使用 zipfile 库,然而,它的官方文档中却明确标注“此模块目前不能处理分卷 ZIP...

Python 文件操作之读取文件(read),文件指针与写入文件(write),文件打开方式示例

Python 文件操作之读取文件(read),文件指针与写入文件(write),文件打开方式示例

本文实例讲述了Python 文件操作之读取文件(read),文件指针与写入文件(write),文件打开方式。分享给大家供大家参考,具体如下: demo.py(读取文件): # 1....

python通过移动端访问查看电脑界面

python通过移动端访问查看电脑界面

这篇文章主要介绍了python通过移动端访问查看电脑界面,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 看上心意的小姐姐,想看她平时都...

tensorflow -gpu安装方法(不用自己装cuda,cdnn)

TensorFlow™是一个基于数据流编程(dataflow programming)的符号数学系统,被广泛应用于各类机器学习(machine learning)算法的编程实...