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

相关文章

PyQt5固定窗口大小的方法

PyQt5固定窗口大小的方法

直接以数值固定大小 根据屏幕大小固定大小 禁止最大化按钮 MainWindow.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint...

Python读取数据集并消除数据中的空行方法

如下所示: # -*- coding: utf-8 -*- # @ author hulei 2016-5-3 from numpy import * import operator...

在自动化中用python实现键盘操作的方法详解

原来在robotframework中使用press key方法进行键盘的操作,但是该方法需要写被操作对象的locator,不是很方便,现在找到了一种win32api库写键盘操作的一个方法...

Django模板Templates使用方法详解

Django模板Templates使用方法详解

一、django的模板: 在settings.py的文件中可以看到并设置这个模板。 1.直接映射: 通过建立的文件夹(templates)和文件(html)来映射。 <!D...

Python中的元类编程入门指引

回顾面向对象编程 让我们先用 30 秒钟来回顾一下 OOP 到底是什么。在面向对象编程语言中,可以定义 类,它们的用途是将相关的数据和行为捆绑在一起。这些类可以继承其 父类的部分或全部性...