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 PEP的一些知识

简单了解python PEP的一些知识

前言 或许你是一个初入门Python的小白,完全不知道PEP是什么。又或许你是个学会了Python的熟手,见过几个PEP,却不知道这玩意背后是什么。那正好,本文将系统性地介绍一下PEP,...

Python设计模式之命令模式原理与用法实例分析

Python设计模式之命令模式原理与用法实例分析

本文实例讲述了Python设计模式之命令模式原理与用法。分享给大家供大家参考,具体如下: 命令模式(Command Pattern):将请求封装成对象,从而使可用不同的请求对客户进行参数...

Python列表(list)常用操作方法小结

常见列表对象操作方法: list.append(x) 把一个元素添加到链表的结尾,相当于 a[len(a):] = [x] 。 list.extend(L) 将一个给定列表中的所有元素都...

Python学习笔记之函数的参数和返回值的使用

Python学习笔记之函数的参数和返回值的使用

01、函数参数和返回值的作用 函数根据 有没有参数 以及 有没有返回值,可以相互结合,共有四种: 无参数 无返回值 无参数 有返回值 有参数 无返回值 有参数 有返回值...

Python 实现使用dict 创建二维数据、DataFrame

Python 实现使用 dict 创建二维数据 dict 的 keys、values 分别作为二维数据的两列 In [16]: d = {1:'aa', 2:'bb', 3:'cc'...